`

dubbo rest 服务学习笔记(一)【原创】

阅读更多
    dubbo是很好的服务治理工具,包含了注册,路由,监控,管理控制台等几个部分,对分析企业的服务依赖和管理有很大的帮助。具体可参看官方文档。
     目前我们公司有很多系统交叉提供服务,服务之间缺少必要的监控,对后续系统的重构都带来很大的困难。同时,由于webservice太重,复杂度高,相对来说采用http+json的交换性能较快,复杂性低。因此我们准备在公司内部主推dubbo+rest的服务。采用dubbo发布的rest服务,既能采用传统的http访问方式,又能采用dubbo客户端访问,可以对原有的服务进行透明的升级。以下是dubbo+rest的开发过程:
1)maven配置:pom.xml
  
<dependency>
                <groupId>javax.ws.rs</groupId>
                <artifactId>javax.ws.rs-api</artifactId>
                <version>${jaxwsrs_version}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-jaxrs</artifactId>
                <version>${resteasy_version}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-client</artifactId>
                <version>${resteasy_version}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-netty</artifactId>
                <version>${resteasy_version}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-jdk-http</artifactId>
                <version>${resteasy_version}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-jackson-provider</artifactId>
                <version>${resteasy_version}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-jaxb-provider</artifactId>
                <version>${resteasy_version}</version>
            </dependency>
            <dependency>
                <groupId>com.esotericsoftware.kryo</groupId>
                <artifactId>kryo</artifactId>
                <version>${kryo_version}</version>
            </dependency>
            <dependency>
                <groupId>de.javakaffee</groupId>
                <artifactId>kryo-serializers</artifactId>
                <version>${serializers_version}</version>
            </dependency>
            <dependency>
                <groupId>de.ruedigermoeller</groupId>
                <artifactId>fst</artifactId>
                <version>${fst_version}</version>
            </dependency>
            <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>${dubbo.version}</version>
        </dependency>

     2)接口类:RestDemoService
       
package cn.gov.zjport.dubborest.service.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import cn.gov.zjport.dubborest.pojo.User;

@Path("/restdemo")
public interface RestDemoService {

	@GET
	@Path("/{param}")
	@Produces(MediaType.TEXT_PLAIN)
	public String search(@PathParam("param")  String param);
	
	@GET
	@Path("/userget")
	@Consumes({MediaType.APPLICATION_XML})
	@Produces({MediaType.APPLICATION_JSON})
	public User get(@QueryParam("name") String name);
	
	@POST
	@Path("/userpost")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public User post(User user);
}

如果采用dubbo客户端调用,必须将rest 相关annotation写在接口上,采用传统http访问方式,则可以写在实现类上
    3)实现类
   
package cn.gov.zjport.dubborest.service.rest.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.gov.zjport.dubborest.pojo.User;
import cn.gov.zjport.dubborest.service.rest.RestDemoService;
import cn.gov.zjport.dubborest.service.system.SettingService;

@Service("restDemoService")
public class RestDemoServiceImpl implements RestDemoService{
	@Resource
	private SettingService settingService;
	
	    
	
	public String search(String param) {
		return settingService.getName(param);
	}
	
	public User get(String name){
		User user=new User();
		user.setId(100L);
		user.setName(name+"abc");
		return user;
	}
	
	public User post(User user){
		user.setName(user.getName()+"xyz");
		return user;
	}
}

4.POJO: user
package cn.gov.zjport.dubborest.pojo;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String name;
	private Long id;
	
	public User(){
		
	}
	
	public User(String name){
		this.name=name;
	}
	

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
}

5. spring 配置文件
  
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
	<!-- 注解驱动 -->
	<context:annotation-config />
	<context:component-scan base-package="cn.gov.zjport.dubborest.service" >
    </context:component-scan>
</beans>

6. dubbo配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--
 - Copyright 1999-2011 Alibaba Group.
 -  
 - Licensed under the Apache License, Version 2.0 (the "License");
 - you may not use this file except in compliance with the License.
 - You may obtain a copy of the License at
 -  
 -      http://www.apache.org/licenses/LICENSE-2.0
 -  
 - Unless required by applicable law or agreed to in writing, software
 - distributed under the License is distributed on an "AS IS" BASIS,
 - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 - See the License for the specific language governing permissions and
 - limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <dubbo:application name="dubborest-webapp" owner="dubborest" organization="zjport"/>

    <dubbo:registry address="zookeeper://192.168.3.110:2181"/>

    <!--uncomment this if you want to test dubbo's monitor-->
    <!--<dubbo:monitor protocol="registry"/>-->

    <!-- here we demonstrate both annotation-based and xml-based configs -->
    <dubbo:annotation package="cn.gov.zjport.dubborest.service" />

    <!-- use tomcat server -->
    <dubbo:protocol name="rest" port="7056" contextpath="dubborest-webapp" server="servlet"
                    extension="com.alibaba.dubbo.rpc.protocol.rest.support.LoggingFilter"/>

	<dubbo:service interface="cn.gov.zjport.dubborest.service.rest.RestDemoService" ref="restDemoService"  protocol="rest"  timeout="2000" connections="100" validation="true"/>
</beans>

7. web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<display-name>dubborest</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/config/beans.xml</param-value>
	</context-param>
	<filter>
		<filter-name>Encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>Encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<listener>
        <listener-class>com.alibaba.dubbo.remoting.http.servlet.BootstrapListener</listener-class>
    </listener>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

其中beans.xml包含了4.5两个配置文件
8.将服务在tomcat中启动即可访问。
9.采用传统http访问方式,可以做一个测试页面测试。
<html>
		<head>
				<script type="text/javascript" src="./jquery.js"></script>
				<script>
						function submitData(){
							$.ajax({
							  url:"http://192.168.180.15:7056/dubborest-webapp/restdemo/userpost",
							  type:"POST",
							  data:$("#name").val(),
							  contentType:"application/json; charset=utf-8",
							  dataType:"json",
							  async:false,
							  success:function(msg){
							    alert(msg.name);
							  }
							})
						}
				</script>
		</head>
		<body>
				<a href="http://192.168.180.15:7056/dubborest-webapp/restdemo/userget?name=ggg">test dubbo rest get</a>
				<br>
				<a href="http://192.168.180.15:7056/dubborest-webapp/restdemo/kkk">test dubbo rest get by path</a>
				<br>
				please use IE browser POST
				<form id="userForm" name="userForm">
						<input type="text" id="name" name="name" value="{&quot;name&quot;:&quot;abc&quot;}">
						<input type="button" value="test dubbo object post" onclick="submitData();">
				</form>
		</body>
</html>

10.采用dubbo客户端访问方式(消费端)在另外一篇写,文章太长。
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    dubbo学习笔记.pdf

    【Dubbo学习笔记】 Dubbo是一款高性能、轻量级的Java RPC框架,它旨在提供面向接口的远程方法调用、智能容错与负载均衡、服务自动注册与发现等核心功能,帮助开发者构建分布式服务架构。以下是对Dubbo基础知识、...

    dubbo学习例题代码资源

    Dubbo,一款由阿里巴巴开源的高性能Java RPC框架,是服务治理的典型代表,广泛应用于分布式系统中。本资源包包含了几个关键的学习示例,旨在帮助开发者深入理解并掌握Dubbo的核心概念和技术。 1. **Dubbo核心组件**...

    dubbo:dubbo学习笔记

    本文将基于"Dubbo学习笔记"这一主题,深入解析Dubbo的核心概念和技术细节。 一、Dubbo简介 1.1 Dubbo的目标 Dubbo旨在简化分布式服务开发,通过提供服务接口、服务注册与发现、服务调用、服务监控等功能,帮助...

    springcloud笔记.pdf

    【SpringCloud笔记】是关于微服务架构的学习资料,主要涵盖了SpringCloud的基本概念、核心组件以及实战技巧。在学习SpringCloud之前,需要具备一定的基础知识,包括IDEA、JDK8、Maven、SpringBoot以及Linux环境的...

    周阳SpringCloud课堂笔记

    # SpringCloud课堂笔记知识点解析 ## 一、微服务概述 ### 1.1 微服务定义 微服务架构作为一种新兴的设计模式,旨在通过将单个应用程序分解为多个小型、独立的服务来提升软件的可扩展性和灵活性。这些服务通常遵循...

    SpringCloud微服务笔记

    5. **Dubbo**:阿里巴巴开源的服务框架,支持高性能的 RPC 服务输出和输入,与 Spring 框架无缝集成。 #### 八、微服务架构 1. **定义**:微服务架构是一种将应用分解为一系列小服务的设计模式,每个服务独立运行...

    drp项目 开发 Java程序员

    12. **微服务架构**:理解微服务的概念,如何通过Spring Cloud或Dubbo实现服务拆分,提高系统的可扩展性和可维护性。 13. **DRP业务流程**:深入理解DRP业务流程,包括采购、销售、库存管理等,将业务逻辑有效地...

Global site tag (gtag.js) - Google Analytics