Spring Cloud(隨筆) - Hystrix

Spring Cloud - Hystrix

  • 斷路器,線程隔離,服務降級,服務熔斷

啓用

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>


@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class ServiceApplication 

fallback + Cache

@CacheResult()
    @HystrixCommand(commandKey="getUser", groupKey="userGroup",fallbackMethod = "getUserFallback")
    public User getUser(@CacheKey Long id){
        return restTemplate.getForObject("http://SPCD-USER/user/{1}",User.class,id);
    }

    public User getUserFallback(Long id){
        return new User(-1,"-1","-1","-1");
    }

    @CacheRemove(commandKey="getUser")
    @HystrixCommand()
    public void updateUser(@CacheKey Long id){
        logger.info("in UserService method updateUser id: {}",id);
    }

@GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Long id){
        userService.getUser(id); // 只請求一次
        userService.getUser(id);
        userService.getUser(id);
        userService.getUser(id);
        return userService.getUser(id);
        
        //return userClient.getUser(id);
    }

Hystrix 緩存 : 生命週期爲 一個 request , 且 Hystrix 超時時間 需設置大於 Ribbon 超時時間

Feign + fallback

配置文件啓用 hystrix

feign:
  hystrix:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 500
        readTimeout: 10000

添加 fallback

@FeignClient(name="spcd-user",fallback = UserClientFallBack.class)
public interface UserClient {

    @GetMapping("/getDate")
    String getDate(@RequestParam("name") String name);

    @GetMapping("/user/{id}")
    User getUser(@PathVariable("id") Long id);
}


@Component
public class UserClientFallBack implements UserClient {

    @Override
    public String getDate(String name) {
        return "SPCD-USER get date fail";
    }

    @Override
    public User getUser(Long id) {
        return new User(-1,"-1","-1","-1");
    }
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章