【SpringCloud】(十二):Fegion的Hystrix支持

时间:2022-08-31 19:48:15

  Fegion也支持Hystrix。当服务提供者出现异常的时候,使用Hystrix回调方法。


【SpringCloud】(十二):Fegion的Hystrix支持


  在前面文章中提到的microservice-comsumer-movie-feign的基础上进行修改,主要是有一个回调的方法。


启动类:

package com.dynamic.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ComsumerMovieFeignApplication {

public static void main(String[] args) {
SpringApplication.run(ComsumerMovieFeignApplication.class, args);
}
}


Controller

package com.dynamic.cloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.dynamic.cloud.entity.User;
import com.dynamic.cloud.feign.UserFeignClient;

@RestController
public class MovieController {

@Autowired
private UserFeignClient userFeignClient;

@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id)
{
return this.userFeignClient.findById(id);
}
}


UserFeignClient 
package com.dynamic.cloud.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.dynamic.cloud.entity.User;

@FeignClient(name="microservice-provider-user",fallback =HystrixClientFallback.class)
public interface UserFeignClient {

@RequestMapping(value="/simple/{id}",method = RequestMethod.GET) //只能是RequestMapping
public User findById(@PathVariable("id") Long id); //@PathVariable需要设置括号中的名称

}

@FeignClient,要用name 和 fallback 

HystrixClientFallback要实现UserFeignClient,并且加入到容器中。

package com.dynamic.cloud.feign;

import org.springframework.stereotype.Component;
import com.dynamic.cloud.entity.User;

@Component
public class HystrixClientFallback implements UserFeignClient {

@Override
public User findById(Long id) {

User user = new User();
user.setId(0L);
return user;
}

}

  启动Eureka,用户微服务和修改后的电影微服务。正常情况下,电影微服务调用用户微服务显示数据,当用户微服务出现异常时。电影微服务执行回调方法。


 【SpringCloud】(十二):Fegion的Hystrix支持