再次说明FeigApi作用了抽取共用代码给Feign和ServiceA使用的,哪里会有共用代码?这就是需要Feign需要访问的ServiceA的几个接口信息 。
package com.pumpkin.service;
import com.pumpkin.dto.User;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/user")
public interface FeignService {
@RequestMapping(value = "/hello1.do", method = RequestMethod.GET)
String hello(@RequestParam("name") String name);
@RequestMapping(value = "/hello2.do", method = RequestMethod.GET)
User hello(@RequestParam("name") String name, @RequestParam("sex") Integer sex);
@RequestMapping(value = "/hello3.do", method = RequestMethod.POST)
String hello(@RequestBody User user);
}
package com.pumpkin.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.pumpkin.dto.User;
import com.pumpkin.service.FeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/feign")
public class FeignController {
@Autowired
private FeignService feignService;
@RequestMapping(value = "/hello.do", method = RequestMethod.GET)
public String feignHello() {
StringBuilder sb = new StringBuilder();
sb.append(feignService.hello("MIMI")).append("\n");
sb.append(feignService.hello("MIMI", 20)).append("\n");
sb.append(feignService.hello(new User("MIMI", 20))).append("\n");
return sb.toString();
}
}
package com.pumpkin.controller;
import com.pumpkin.dto.User;
import com.pumpkin.service.FeignService;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FeignController implements FeignService {
private final Logger LOGGER = Logger.getLogger(getClass());
@Override
public String hello(@RequestParam("name")String name) {
return "hello";
}
@Override
public User hello(@RequestParam("name")String name, @RequestParam("sex")Integer sex) {
LOGGER.info("name=" +name+ " ,sex=" +sex);
return new User("pumpkin", 0);
}
@Override
public String hello(@RequestBody User user) {
return "hello user=" +user.toString();
}
}
Spring Cloud Feign是对Spring Cloud Ribbon和Spring Hystrix封装整合。这篇随笔主要介绍了Spring Cloud Feign的简单使用,对于如何进行服务熔断和降级并没有涉及,但从使用层面来讲也就是几个注解的问题,只要对Hystrix机制有一定的理解,使用起来是非常容易的,另外Feign并没有对Hysrix的请求合并和请求缓存进行封装,所以需要这些功能的话,只能使用回Ribbon了。
六、参考资料
Spring Cloud微服务实战-翟永超。本系列的学习都是参考该书籍学习的,同时源码使用的Spring Boot和Spring Cloud的版本也与该书保持一致。
七、源码
码云地址:git@gitee.com:pumpkingg/Spring-Cloud-Study.git 该篇随笔对应的代码是master分支下命名为blog3的Tag