dubbo个人感觉很牛逼的功能就是支持多协议了,可以把服务暴露成各种协议 如: http,webservice,hessian,rmi...等
这里简单介绍下同时发布成dubbo和webservice两种协议
代码在 dubbo(二)注册中心zookeeper 的基础上进行改造
在tm-dubbo-provider 和 tm-dubbo-consumer的pom.xml 中增加ws的依赖
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-simple</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>6.1.26</version>
<exclusions>
<exclusion>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
在 tm-dubbo-api 中增加接口
public interface SystemApi {
String uuid(Integer id);
}
在 tm-dubbo-provider中
增加实现SystemApiService.java
public class SystemApiService implements SystemApi {
@Override
public String uuid(Integer id) {
return USERS.get(id.hashCode() % USERS.size()) + ":" + UUID.randomUUID();
}
private static final List<String> USERS = new ArrayList<>();
static {
USERS.add("唐僧");
USERS.add("八戒");
USERS.add("悟空");
USERS.add("沙僧");
}
}
修改 spring-dubbo-provider.xml
<dubbo:application name="tm-dubbo-provider"/>
<dubbo:protocol name="webservice" port="8082"/>
<dubbo:protocol name="dubbo" port="20880" />
<dubbo:registry address="zookeeper://192.168.2.167:2181"/>
<dubbo:service interface="cn.majingjing.tm.UserApi" ref="UserApi" protocol="webservice"/>
<dubbo:service interface="cn.majingjing.tm.SystemApi" ref="SystemApi" protocol="dubbo"/>
<bean id="UserApi" class="cn.majingjing.tm.UserApiService" />
<bean id="SystemApi" class="cn.majingjing.tm.SystemApiService" />
在 tm-dubbo-consumer中
增加controller的调用
@RequestMapping("/dubbo/t2")
public Object t2(Integer id) {
String name = systemApi.uuid(id);
System.out.println(name);
return name;
}
修改 spring-dubbo-consumer.xml
<dubbo:application name="tm-dubbo-consumer" />
<dubbo:registry address="zookeeper://192.168.2.167:2181" />
<dubbo:protocol name="webservice" port="8082" />
<dubbo:protocol name="dubbo" port="20880" />
<dubbo:reference id="userApi" interface="cn.majingjing.tm.UserApi" protocol="webservice" />
<dubbo:reference id="systemApi" interface="cn.majingjing.tm.SystemApi" protocol="dubbo" />
启动服务,打开浏览器访问 dubbo的管理控制台 http://localhost:18080 可以看到有两个服务提供出来了
可以看到UserApi发布成了webservice服务,SystemApi发布成了dubbo服务
访问浏览器查看服务是否成功
http://localhost:8080/tm-dubbo-consumer/dubbo/t1?id=1
http://localhost:8080/tm-dubbo-consumer/dubbo/t2?id=1
源代码地址: http://git.oschina.net/majinding/tm-dubbo/tree/tag-v1.0.3