1、通过maven引入如下所示的jar包。
<!-- 引入 Feign, 可以以声明的方式调用微服务 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 引入服务容错 Hystrix 的依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、进行如下配置。
调用方
#建议开启,否则zuul的balancer有可能会出现无法转发的问题
spring.main.allow-bean-definition-overriding=true
#注册到eureka服务
eureka.client.service-url.defaultZone=http://server1:8000/eureka/
#开启熔断降级,默认是关闭的,所以需要手动开启
feign.hystrix.enabled=true
#如下配置后,serviceId为service-user
spring.application.name=service-user
提供方
#必须开启,否则网关服务的balancer将会无法分发
spring.main.allow-bean-definition-overriding=true
#注册到eureka服务
eureka.client.service-url.defaultZone=http://server1:8000/eureka/
#开启熔断降级
feign.hystrix.enabled=true
#如下配置后,serviceId为service-comment
spring.application.name=service-comment
zuul
zuul:
prefix: /service-route
routes:
user: #用户信息服务,前缀就是你配置的context-path
path: /context-path/user/**
serviceId: zy-easygo-user
strip-prefix: false
comment: #用户评论服务,前缀就是你配置的context-path
path: /context-path/comment/**
serviceId: zy-easygo-comment
strip-prefix: false
ribbon: #设置ribbon的超时时间小于zuul的超时时间,如果不配置的话,可能会频繁出现504超时
ReadTimeout: 10000
ConnectTimeout: 10000
3、配置完成后,编写feign接口。
/**
* 在调试阶段可以不用配置熔断器,此时会在浏览器端打印500并提示:服务出现错误并且未配置熔断器。
* 如果太早配置熔断降级,可能会出现无法找到异常信息的情况,请知悉。
* 如果不配置熔断降级的注解应该这样写
* @FeignClient(value = "service-comment")
*/
//value就是你刚刚配置的application.name,fallback就是你的熔断降级业务逻辑
@FeignClient(value = "service-comment", fallback = CommentClientHystrix.class)
public interface CommentClient {
@RequestMapping(value = "/context-path/comment/query", method = RequestMethod.POST)
Object getUserInfo(@RequestParam("userId") String openid);
}
//我的服务提供方返回的数据类型是Map。
接收参数的对象类型必须和服务提供方返回的参数一模一样,否则只能用map或者是object接收。
我个人喜欢在service层中使用object来声明返回值类型,然后在service层的实现类中在使用强转+get的方式来获取到map中的内容。
如果使用map的话,则获取参数直接用get("key")方法即可。
4、熔断器
//需要加入@Component注解,并且实现你的feign接口才能在你的fallback中配置。
@Component
public class CommentClientHystrix implements CommentClient {
@Override
public Object getUserInfo(String openid) {
System.out.println("熔断");
return null;//在这里返回你的熔断降级策略,我这里只是演示直接返回了null。
}
}
5、调用
feign的强大之处就在于调用别的服务就像方法一样简单。
你只需要注入feign接口,就能完成使用。
@Autowired
private CommentClient cc;
@Override
public Object check(String openid) {
return cc.getUserInfo(openid);
}
6、此时如果你打开断点调试,就能在这个object中看到你需要的内容了。是不是非常简单。