Spring Cloud 之 Feign 客户端调用服务

FeignClient用于调用其他服务,相对Spring RestTemplate使用更简单,

新建一个模块,feignclient,

1、maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--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>
<!--hystrix DashBoard 依赖包-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

2、启动类上添加注解,

@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
@EnableHystrixDashboard

3、启动类里添加Hystrix Bean,

@Bean
public ServletRegistrationBean getServlet() {
    HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
    ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
    registrationBean.setLoadOnStartup(1);
    registrationBean.addUrlMappings("/actuator/hystrix.stream");
    registrationBean.setName("hystrixStreamServlet");
    return registrationBean;
}

4、配置文件,

spring:
  application:
    name: feignclient
server:
  port: 8090
  shutdown: graceful
eureka:
  client:
    service-url:
      defaultZone: http://peer1:8761/eureka/

feign:
  hystrix:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000

#hystrix的超时时间
hystrix:
  dashboard:
    proxy-stream-allow-list: "*"

5、Feign配置类,

@Configuration
public class FeignConfig {

    @Bean
    public Retryer feignRetryer() {
        return new Retryer.Default(100, TimeUnit.SECONDS.toMillis(1), 5);
    }
}

6、写一个api接口,

@RestController
@RequestMapping("feign")
public class FeignController {
    @Autowired
    private LogClient logClient;

    @GetMapping("getInfo")
    public String getInfo() {
        String info = "log info2";
        return logClient.getInfo(info);
    }
}

LogClient类,

@Service
@FeignClient(value = "logservice",
        configuration = FeignConfig.class,
        fallback = LogFallback.class)
public interface LogClient {
    @RequestMapping(value="/log/logInfo2", method = RequestMethod.GET)
    String getInfo(String info);
}

LogFallback类,

public class LogFallback implements LogClient {
    @Override
    public String getInfo(String info) {
        return "logservice timeout!";
    }
}

7、访问接口,http://peer1:8090/feign/getInfo

扫描二维码关注公众号,回复: 12718614 查看本文章

猜你喜欢

转载自blog.csdn.net/suoyx/article/details/113826116