1、修改配置:
# #指定某一种协议 # protocol: # name: dubbo # port: 20882 # #指定多种协议 protocols: pro1: id: dubbo1 name: dubbo port: 20881 host: 0.0.0.0 pro2: id: dubbo2 name: dubbo port: 20882 host: 0.0.0.0
2、服务提供者代码:
对于"default"版本的服务,指定使用pro1协议
对于"async"版本的服务,指定使用pro2协议
1 package com.yas.serviceprovider.protocol; 2 3 import com.yas.api.SiteService; 4 import org.apache.dubbo.config.annotation.Service; 5 6 @Service(version = "default", protocol = "pro1") 7 public class ProtocolImpl1 implements SiteService { 8 @Override 9 public String getName(String name) { 10 return "pro1:" + name; 11 } 12 }
package com.yas.serviceprovider.protocol; import com.yas.api.SiteService; import org.apache.dubbo.config.annotation.Service; @Service(version = "async",protocol = "pro2") public class ProtocolImpl2 implements SiteService { @Override public String getName(String name) { return "pro2:" + name; } }
使用zookeeper客户端连接,通过命令查询znode节点的数据:
./zkCli.sh ls /dubbo/com.yas.api.SiteService/providers
查询的内容如下(经过URL解码):
dubbo://192.168.0.101:20881/com.yas.api.SiteService?anyhost=true&application=site-service-boot-provider&bean.name=ServiceBean:com.yas.api.SiteService:default&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&interface=com.yas.api.SiteService&methods=getName&pid=9832®ister=true&release=2.7.3&revision=default&side=provider×tamp=1635987213625&version=default, dubbo://192.168.0.101:20882/com.yas.api.SiteService?anyhost=true&application=site-service-boot-provider&bean.name=ServiceBean:com.yas.api.SiteService:async&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&interface=com.yas.api.SiteService&methods=getName&pid=9832®ister=true&release=2.7.3&revision=async&side=provider×tamp=1635987214582&version=async
3、服务消费者代码:
消费者调用某个version的服务,服务端会使用其绑定的protocol进行完成消息的传输。
package com.yas.serviceconsumer.controller; import com.yas.api.SiteService; import org.apache.dubbo.config.annotation.Reference; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ProtocolSiteController { @Reference(version = "default") SiteService siteService1; @RequestMapping("/pro1") public String getName1(@RequestParam("name") String name){ return siteService1.getName(name); } @Reference(version = "async") SiteService SiteService2; @RequestMapping("/pro2") public String getName2(@RequestParam("name") String name){ return SiteService2.getName(name); } }
4、测试:
使用postman请求地址:http://localhost:8000/pro1?name=zhangsan
得到响应为:pro1:zhangsan
使用postman请求地址:http://localhost:8000/pro2?name=zhangsan
得到响应为:pro2:zhangsan