1、提供方配置文件:
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
2、提供方代码:
1 package com.yas.serviceprovider.timeout; 2 3 import com.yas.api.SiteService; 4 import org.apache.dubbo.config.annotation.Service; 5 //1.如果服务端设置了timeout,而客户端没有设置,表示客户端采用服务端一样的timeout 6 //2.如果服务端的实际执行时间比设置的timeout要长,那么会打印超时日志,但服务会正常执行 7 @Service(version = "timeout",timeout = 4000) 8 public class TimeoutSiteServiceImpl implements SiteService { 9 @Override 10 public String getName(String name) { 11 try { 12 Thread.sleep(5000); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 return "timeout:"+name; 17 } 18 }
3、接口层新增一个stub类:
这里用到了代理模式。
这个类必须和SiteService接口放在同一个包下(约定)。
1 package com.yas.api; 2 3 public class SiteServiceStub implements SiteService { 4 private SiteService siteService; 5 6 public SiteServiceStub(SiteService siteService){ 7 this.siteService = siteService; 8 } 9 10 @Override 11 public String getName(String name) { 12 try{ 13 return this.siteService.getName(name); 14 }catch (Exception e){ 15 return "stub:"+name; 16 } 17 } 18 }
4、消费方代码:
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 TimeoutController { //客户端未设置timeout,服务端也未设置timeout,则默认为1000毫秒超时 //客户端未设置timeout,服务端设置了timeout,则客户端以服务端设置为准 //如果客户端timeout的时间到了,服务端还没有返回数据,则抛出异常 //如果客户端timeout到之前,已经从服务端获取了响应,则正常执行 @Reference(version = "timeout",timeout = 2000,stub = "true") SiteService siteService; @RequestMapping("/timeout") public String getName(@RequestParam("name") String name){ return siteService.getName(name); } }
5、测试:
使用postman请求地址:http://localhost:8000/timeout?name=zhangsan
结果如下:stub:zhangsan