欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-13 19:45:00
...
    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 rest