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