Dubbo常用功能05设置服务的timeout时间

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、服务消费者代码:

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)
    SiteService siteService;

    @RequestMapping("/timeout")
    public String getName(@RequestParam("name") String name){
        return siteService.getName(name);
    }
}

解释:服务提供者设定了timeout是4000ms,但服务提供者的代码执行,至少需要5000ms。

因此服务提供者方,会打印warn级别的日志(需要配置log4j)。

而服务的消费方,设定了timeout是2000ms,因此会抛出超时异常。

4、测试:

使用postman请求地址:http://localhost:8000/timeout?name=zhangsan

得到响应如下:

如果将客户端的timeout设置为12000ms,则正常情况下会正确获得服务提供方的返回结果。

原文地址:https://www.cnblogs.com/asenyang/p/15507436.html