目錄
背景
eureka1 中包含一堆服務:
aa1
aa1
vplm
vslm
aa-gateway(註冊ip+端口 :10.10.xx.xx:9901/)
等等.............
eureka2 中包含一堆服務:
bb1
bb2
bb-gateway(註冊ip+端口 :10.10.xx.xx:9902/)
customer-im
employee
等等.............
業務需求
vslm 模塊需要調用customer-im 模塊的接口,而vslm註冊在eureka1中,customer-im註冊在eureka2 中
現在需要vslm跨eureka調用customer-im服務接口
Demo實現
eureka相關配置及註解略
customer-im 模塊暴露的接口
@ApiOperation("跨eureka聯調測試")
@GetMapping("/test/{id}")
public String connTest(@PathVariable String id){
//方法用於測試
String out = "聯調成功訪問客戶模塊並返回數據:\t" + id;
System.out.println(out);
//模擬超時情況觸發熔斷
/*try {
Thread.sleep(60000L);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
return out;
}
vslm消費服務
yml配置url
#跨eureka走網關
feign_api_url:
customerName: customer
customerUrl: 10.10.xx.xx:9902/customer-im/
feign:
hystrix:
enabled: true
feign接口編寫:CustomerFeignApi
其中url給的是:eureka2的網關的服務地址(customerUrl: 10.10.xx.xx:9902/customer-im/)
即:調的是gateway2網關,後面加的是服務實力名,讓網關自己去註冊中心找需要調用的服務實例(實現負載均衡ribbon)
/**
* @Description
* @Author by mocar小師兄
* @Date 2020/6/29 11:45
**/
@FeignClient(name = "${feign_api_url.customerName}",url = "${feign_api_url.customerUrl}",fallbackFactory = CustomerFeignApiImpl.class)
public interface CustomerFeignApi {
/***
* 功能描述: 測試聯調
* 〈〉
* @Param: []
* @Return: java.lang.String
* @Author: by
* @Date: 2020/6/29 11:51
*/
@GetMapping("/customer/test/{id}")
String connTest(@PathVariable String id);
}
熔斷機制類:CustomerFeignApiImpl
@Component
public class CustomerFeignApiImpl implements FallbackFactory<CustomerFeignApi> {
private static final Logger logger = LoggerFactory.getLogger(CustomerFeignApiImpl.class);
@Override
public CustomerFeignApi create(Throwable cause) {
return new CustomerFeignApi(){
@Override
public String connTest(String id) {
logger.error("fallback;arg was: {}, exception was: {}, reason was: {}",id ,cause.toString(),cause.getMessage());
return cause.getMessage();
}
};
}
}
controller層的接口測試:
@Autowired
private CustomerFeignApi customerFeignApi;
@GetMapping("/test/{id}")
public String test(@PathVariable("id") String id){
System.out.println("入參爲" + id);
String connTest = customerFeignApi.connTest(id);
//如果feign調用出現網絡等異常,會執行rollback實現類中重寫的方法,並返回重寫的方法的return值
//如果正常,則返回調用的接口的返回值
System.out.println(connTest);//
return connTest;
}
運行結果:(下面是模擬熔斷的結果輸出)
入參爲nnnnnhhhhhhhh
2020-06-29 15:29:04 [hystrix-customer-1] ERROR c.h.v.s.f.f.CustomerFeignApiImpl.connTest - fallback;arg was: nnnnnhhhhhhhh, exception was: feign.FeignException: status 500 reading CustomerFeignApi#connTest(String), reason was: status 500 reading CustomerFeignApi#connTest(String)
status 500 reading CustomerFeignApi#connTest(String)
調用成功