文章目录
- feign
- pom.xml引入
- 启用feign支持
- 使用
- hystrix
- pom.xml中添加
- 启用hystrix支持
- 实现fallback对应的hystrix实现类
feign和hystrix都是springcloud的组件,因为2者关系比较密切,所以放在一起说。
feign
feign是假装,伪装的意思。
feign 是声明式的web服务客户端。
pom.xml引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启用feign支持
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.test.*"}) // 开启Feign支持
public class Application{ }
使用
代码:
@Service("userService")
@FeignClient(value = "auth-server", fallback = UserServiceHystrix.class)
public interface UserService {
@RequestMapping(value = "/user/queryUser", method = RequestMethod.POST)
JsonResult queryUser(@RequestBody User user) throws SystemException;
}
调用UserService.queryUser()方法,
请求的是 auth-server 服务下的 /user/queryUser 路径。
相比于将url写在代码里是不是优雅了很多。
而且feign还有负载均衡的作用。
hystrix
hystrix 的作用是熔断。
pom.xml中添加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
启用hystrix支持
代码:
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.test.*"}) // 开启Feign支持
@EnableHystrix // 这行代码表示启用hystrix支持
public class Application{ }
配置文件:
# 是否启用feign的hystrix 一般推荐设置为true
feign.hystrix.enabled=true
# hystrix的超时时间
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=200000
# 是否启用Hystrix的超时时间
hystrix.command.default.execution.timeout.enabled=false
实现fallback对应的hystrix实现类
当超时或者发生异常的时候,就会调用fallback对应的方法,代码:
@Component
@ComponentScan(basePackages = {"com.test"})
public class UserServiceHystrix implements UserService {
private static final Logger iLogger = LoggerFactory.getLogger(UserServiceHystrix.class);
@Override
public JsonResult queryUser(User user) {
iLogger.error("auth-server.queryUser 权限熔断器——调用接口出现异常");
JsonResult result = new JsonResult(new HystrixException());
return result;
}
}