本人也是springcloud小白一個掸茅,把平時工作中遇到的問題整理出來方便日后查看也方便大家遇到同樣的問題能有個解決方案雳攘。
1.feign做調用服務的客戶端時茴恰,設置超時時間和ribbon的超時時間巴粪。
主要解決某些需要長時間響應的接口,不至于到了超時時間而進入fallback方法民宿。
ribbon.ReadTimeout=5000(默認)
服務名.ribbon.ReadTimeout 指定服務設置
hystrix.command.類名#方法名(參數類型).execution.isolation.thread.timeoutInMilliseconds 來設置某個方法的超時時間携龟。
確保Hystrix超時時間配置為長于配置的Ribbon超時時間
2.feign客戶端在部署時若有contextpath應該設置 path="/***"來匹配你的服務名。
@FeignClient(name = "demoservice", path = "/demoservice", fallbackFactory = FallbackFactory.class)
public interface DemoService {
@RequestMapping(method = RequestMethod.GET, value = "/user/{id}")
String getUser(@PathVariable("id") String id);
@Component
class FeignClientFallbackFactory implements FallbackFactory<DemoService> {
private static final Logger LOGGER = LoggerFactory.getLogger(FeignClientFallbackFactory.class);
@Override
public DemoService create(final Throwable cause) {
return new DemoService() {
@Override
public String getUser(String id) {
LOGGER.error("fallback reason was:", cause);
Map<String, Object> map = new HashMap<>();
map.put("msg", "請求服務端接口失敗勘高,執(zhí)行fallback方法");
return JSON.toJSONString(map);
}
};
}
}
}
我們正常把注冊中心,服務提供方和服務調用方啟起來坟桅,在本地測試可以通過华望,在docker里就訪問不到調用不到提供方的服務了。我們通過日志可以分析出fallback的原因是404沒有這個服務仅乓,說明我們的路徑有問題赖舟,查看FeignClient源碼可以看到。
/**
* Path prefix to be used by all method-level mappings. Can be used with or without
* <code>@RibbonClient</code>.
*/
String path() default "";
設置上path這個屬性夸楣,我們就可以正常調用到提供方的服務了宾抓。
3.zuul組件路由有contextpath的服務時,應添加strip-prefix豫喧。
zuul.routes.portal.path=/portal/**
zuul.routes.portal.strip-prefix=false
portal是一個微服務應用石洗,要通過zuul進行反向代理且有contextpath,就可以這么來配置紧显。官方文檔中也有提及讲衫,大家可以自行查閱。
4.zuul集成hystrix不顯示線程池信息的解決辦法孵班。
zuul集成hystrix默認使用的是信號量隔離涉兽,不是線程隔離。
源碼中可以看到默認是信號隔離的方式
private ExecutionIsolationStrategy ribbonIsolationStrategy = SEMAPHORE;
/**
* Isolation strategy to use when executing a {@link HystrixCommand}.
* <p>
* <ul>
* <li>THREAD: Execute the {@link HystrixCommand#run()} method on a separate thread and restrict concurrent executions using the thread-pool size.</li>
* <li>SEMAPHORE: Execute the {@link HystrixCommand#run()} method on the calling thread and restrict concurrent executions using the semaphore permit count.</li>
* </ul>
*/
public static enum ExecutionIsolationStrategy {
THREAD, SEMAPHORE
}
zuul.ribbon-isolation-strategy=THREAD 修改為線程隔離方式