实践Spring Cloud之Feign Posted on 2017-11-03 | In Java | Visitors Feign实现声明式服务调用,将REST服务包装成接口,效果类似本地调用一样 1234<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> 1@EnableFeignClients 接口 123456789101112131415161718192021222324252627282930313233343536/** * @author angi */ @FeignClient("hello-service") public interface HelloService { /** * 无参 * * @return */ @RequestMapping("/hello") String hello(); @RequestMapping(value = "/hello1", method = RequestMethod.GET) String hello(@RequestParam("name") String name); /** * 查询用户 * * @param name * @param age * @return */ @RequestMapping(value = "/hello2", method = RequestMethod.GET) User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age); /** * 新增用户 * * @param user * @return */ @RequestMapping(value = "/hello3", method = RequestMethod.POST) String hello(@RequestBody User user); } 服务端 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253/** * @author angi */ @RefreshScope @RestController public class HelloController { private final Logger logger = Logger.getLogger(getClass()); @Value("${key2}") private String key; @Autowired private DiscoveryClient discoveryClient; @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() throws Throwable { ServiceInstance instance = discoveryClient.getLocalServiceInstance(); int sleepTime = new Random().nextInt(3000); Thread.sleep(sleepTime); logger.info("/hello, host:" + instance.getHost() + ", serviceId:" + instance.getServiceId()); return "Hello, World!" + key; } @RequestMapping(value = "/hello1", method = RequestMethod.GET) public String hello(@RequestParam String name) { return "Hello, " + name; } /** * 查询用户 * * @param name * @param age * @return */ @RequestMapping(value = "/hello2", method = RequestMethod.GET) public User hello(@RequestHeader String name, @RequestHeader Integer age) { return new User(name, age); } /** * 新增用户 * * @param user * @return */ @RequestMapping(value = "/hello3", method = RequestMethod.POST) public String hello(@RequestBody User user) { return "Hello, " + user.getName() + ", " + user.getAge(); } } feign默认使用断路器(hystrix)包裹所有方法,可以全局禁用,也可以局部禁用。 12# 全局禁用hystrix feign.hystrix.enabled=false