1、apolication.yml的配置:
server: port: 8001 dubbo: application: name: site-service-boot-provider registry: address: zookeeper://ubu:2181 scan: base-packages: com.yas.serviceprovider # #指定某一种协议 # protocol: # name: dubbo # port: 20882 # protocol: # name: rest # port: 8787 #指定多种协议 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、服务提供者代码:
1 package com.yas.serviceprovider.impl; 2 3 import com.yas.api.SiteService; 4 import org.apache.dubbo.common.URL; 5 import org.apache.dubbo.config.annotation.Service; 6 import org.apache.dubbo.rpc.RpcContext; 7 8 @Service(version = "url") 9 public class URLSiteServiceImpl implements SiteService { 10 11 @Override 12 public String getName(String name) { 13 URL url = RpcContext.getContext().getUrl(); 14 return "url:" + name+",使用的协议是:"+url.getProtocol()+",端口是:"+url.getPort(); 15 } 16 }
注意第8行,没有指定protocol参数,则表示配置文件中配置的20881和20882端口的服务都会启动。
3、服务消费者的代码:
1 package com.yas.serviceconsumer.controller; 2 3 import com.yas.api.SiteService; 4 import org.apache.dubbo.config.annotation.Reference; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RequestParam; 7 import org.springframework.web.bind.annotation.RestController; 8 9 @RestController 10 public class ProtocolSiteController { 11 12 // @Reference(version = "default",protocol = "") 13 // SiteService siteService1; 14 // 15 // @RequestMapping("/pro1") 16 // public String getName1(@RequestParam("name") String name){ 17 // return siteService1.getName(name); 18 // } 19 // 20 // @Reference(version = "async",protocol = "") 21 // SiteService SiteService2; 22 // 23 // @RequestMapping("/pro2") 24 // public String getName2(@RequestParam("name") String name){ 25 // return SiteService2.getName(name); 26 // } 27 28 @Reference(version = "url",url = "dubbo://127.0.0.1:20882/com.yas.api.SiteService:url") 29 SiteService SiteService3; 30 31 @RequestMapping("/url") 32 public String getName3(@RequestParam("name") String name) { 33 return SiteService3.getName(name); 34 } 35 }
4、测试:
使用postman请求地址:http://localhost:8000/url?name=zhangsan
得到响应:url:zhangsan,使用的协议是:dubbo,端口是:20882