原始的調用客戶端的方式是通過註入restTemplate的方式 通過feign的方式 配置消費者項目cloud-consume pom.xml 依賴jar application.yml 添加啟動feign 可實現錯誤回調 啟動應用類 ClondConsumeApplication.java 添加註 ...
原始的調用客戶端的方式是通過註入restTemplate的方式
restTemplate.getForObject("http://CLIENT/hello", String.class)
通過feign的方式
配置消費者項目cloud-consume
pom.xml
依賴jar
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
application.yml
添加啟動feign 可實現錯誤回調
feign:
hystrix:
enabled: true
啟動應用類
ClondConsumeApplication.java
添加註解@EnableFeignClients
HelloService.java介面
package com.tp.soft.cloudconsume.service; import com.tp.soft.cloudconsume.service.impl.HelloServiceFallback; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(value = "CLIENT", fallback = HelloServiceFallback.class) public interface HelloService { @GetMapping("/hello") String hello(); }
其中CLIENT則為註冊中心被調用的應用名,/hello完全和客戶端業務介面一樣,fallback則為錯誤回調的方法,同時可以防止應用雪崩效應.
HelloServiceFallback.java介面
package com.tp.soft.cloudconsume.service.impl; import com.tp.soft.cloudconsume.service.HelloService; import org.springframework.stereotype.Component; @Component public class HelloServiceFallback implements HelloService { @Override public String hello() { return "request error"; } }
HelloController.java
package com.tp.soft.cloudconsume.controller; import com.tp.soft.cloudconsume.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; @RestController public class HelloController { // @Autowired // RestTemplate restTemplate; @Resource private HelloService helloService; @GetMapping("hi") public String hi(){ //return restTemplate.getForObject("http://CLIENT/hello", String.class); return helloService.hello(); } }
和原來在controller調用介面一模一樣的去調用就可以了
最後的效果: