使用testboot这个项目
why?feign集成ribbon和hystrix,操作更加方便,传参更便捷
使用testboot
pom
<!-- SpringCloud 整合 Feign -->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
启动类start.class新增注解
新增注解
@EnableFeignClients//调用者启动时,打开Feign开关
ribbon类似代理功能
在onemiion工程
单服务中,具体实现如下:
@ApiOperation(value = "获取用户列表", notes = "获取用户列表")
@RequestMapping(value = "/hi2", method = RequestMethod.POST)
@ResponseBody
public String hi2(@RequestBody @ApiParam(value = "用户数据") AppearIcon1 appear) {
logger.info(new Gson().toJson(appear));
return "hi, I'm springboot !"+Hello.hello;
}
在testboot中,新增接口代理,指明代理的服务,以及方法对应的具体路径和参数,与被代理的一致:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import boot.dao.entity.AppearIcon1;
@FeignClient("one-million")
public interface FeignHelloService {
@RequestMapping(value = "/one-million-dev/hi2", method = RequestMethod.POST)
@ResponseBody
public String hi2(@RequestBody AppearIcon1 appear) ;
}
使用:
//feig
@Autowired
private FeignHelloService feign;
@RequestMapping(value = "/hi222", method = RequestMethod.POST)
@ResponseBody
public String hi2(@RequestBody AppearIcon1 appear) {
return feign.hi2(appear);
}
项目启动过后,输入localhost:8092/test/hi222,加上相关请求体即可完成访问
hystrix类似代理功能
0,打开feign开关,在application.yml中新增配置:
feign:
hystrix:
enabled: true
1,代理接口新增fallback类
@FeignClient(name="one-million",fallback=FeignHelloServiceBack.class)
public interface FeignHelloService {
@RequestMapping(value = "/one-million-dev/hi2", method = RequestMethod.POST)
@ResponseBody
public String hi2(@RequestBody AppearIcon1 appear) ;
}
2,新增FeignHelloServiceBack类,实现FeignHelloService 接口,实现的hi2接口的具体逻辑即为fallback
@Component
public class FeignHelloServiceBack implements FeignHelloService{
@Override
public String hi2(AppearIcon1 appear) {
return "back";
}
}
关闭服务,或者修改FeignHelloService 中mapping的路径即可得到返回: