所需依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
服务器提供者配置
############################################################
#
# hystrix 配置信息
#
############################################################
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 5000 # 设置hystrix超时时间,超过5秒触发降级
circuitBreaker: # 配置断路器
enabled: true
requestVolumeThreshold: 10 # 触发熔断最小请求次数,默认:20
sleepWindowInMilliseconds: 15000 # 熔断后过几秒后尝试半开状态(请求重试),默认:5s
errorThresholdPercentage: 50 # 触发熔断的失败率(异常率/阈值),默认:50
使用
package cc.sunni.user.controller;
import cc.sunni.api.controller.user.UserControllerApi;
import cc.sunni.common.Constant;
import cc.sunni.common.utils.R;
import cc.sunni.common.utils.RedisOperator;
import cc.sunni.common.utils.ResultEnum;
import cc.sunni.pojo.bo.UpdateUserInfoBO;
import cc.sunni.pojo.user.AppUser;
import cc.sunni.pojo.vo.AppUserVO;
import cc.sunni.pojo.vo.UserAccountInfoVO;
import cc.sunni.user.service.AppUserService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController implements UserControllerApi {
@Autowired
private AppUserService userService;
@Autowired
private RedisOperator redis;
public R defaultFallback() {
System.out.println("全局降级");
return R.en(ResultEnum.SYSTEM_ERROR_GLOBAL);
}
@Override
@HystrixCommand
public R queryByIds(String userIds) {
if (StringUtils.isBlank(userIds)) {
return R.en(ResultEnum.USER_NOT_EXIST_ERROR);
}
List<AppUserVO> publisherList = new ArrayList<>();
List<String> userIdList = JSONUtil.toList(userIds, String.class);
for (String userId : userIdList) {
// 获得用户基本信息
AppUserVO userVO = getBasicUserInfo(userId);
// 添加到publisherList
publisherList.add(userVO);
}
return R.ok(publisherList);
}
}
@SpringBootApplication
@EnableEurekaClient // 开启eureka client,注册到server中
@EnableCircuitBreaker // 开启hystrix的熔断机制
@ComponentScan(basePackages = {"cc.sunni.user", "cc.sunni.common", "cc.sunni.api"})
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
服务调用者降级
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients({"cc.sunni.api"})
@EnableHystrix
@ComponentScan(basePackages = {"cc.sunni.article", "cc.sunni.common", "cc.sunni.api"})
public class ArticleApplication {
public static void main(String[] args) {
SpringApplication.run(ArticleApplication.class, args);
}
}
# 配置feign
feign:
hystrix:
enabled: true # 打开feign客户端的内置hystrix
package cc.sunni.api.controller.user;
import cc.sunni.api.config.MyServiceList;
import cc.sunni.api.controller.user.fallbacks.UserControllerFactoryFallback;
import cc.sunni.common.utils.R;
import cc.sunni.pojo.bo.UpdateUserInfoBO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@Api(value = "用户信息相关Controller", tags = {"用户信息相关Controller"})
@RequestMapping("user")
@FeignClient(value= MyServiceList.SERVICE_USER, fallbackFactory = UserControllerFactoryFallback.class)
public interface UserControllerApi {
@ApiOperation(value = "获得用户基本信息", notes = "获得用户基本信息", httpMethod = "POST")
@PostMapping("/getUserInfo")
R getUserInfo(@RequestParam String userId);
@ApiOperation(value = "获得用户账户信息", notes = "获得用户账户信息", httpMethod = "POST")
@PostMapping("/getAccountInfo")
R getAccountInfo(@RequestParam String userId);
@ApiOperation(value = "修改/完善用户信息", notes = "修改/完善用户信息", httpMethod = "POST")
@PostMapping("/updateUserInfo")
R updateUserInfo(@RequestBody @Validated UpdateUserInfoBO updateUserInfoBO);
@ApiOperation(value = "根据用户的ids查询用户列表", notes = "根据用户的ids查询用户列表", httpMethod = "GET")
@GetMapping("/queryByIds")
R queryByIds(@RequestParam String userIds);
}
package cc.sunni.api.controller.user.fallbacks;
import cc.sunni.api.controller.user.UserControllerApi;
import cc.sunni.common.utils.R;
import cc.sunni.common.utils.ResultEnum;
import cc.sunni.pojo.bo.UpdateUserInfoBO;
import cc.sunni.pojo.vo.AppUserVO;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
@Component
public class UserControllerFactoryFallback implements FallbackFactory<UserControllerApi> {
@Override
public UserControllerApi create(Throwable throwable) {
return new UserControllerApi() {
@Override
public R getUserInfo(String userId) {
return R.en(ResultEnum.SYSTEM_ERROR_FEIGN);
}
@Override
public R getAccountInfo(String userId) {
return R.en(ResultEnum.SYSTEM_ERROR_FEIGN);
}
@Override
public R updateUserInfo(@Valid UpdateUserInfoBO updateUserInfoBO) {
return R.en(ResultEnum.SYSTEM_ERROR_FEIGN);
}
@Override
public R queryByIds(String userIds) {
System.out.println("进入客户端(服务调用者)的降级方法");
List<AppUserVO> publisherList = new ArrayList<>();
return R.ok(publisherList);
}
};
}
}