版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27828675/article/details/83413711
注意:这里用到的项目都是在之前几篇文章讲解用到的项目工程基础上进行的,在这一系列博客写完后会提供源码地址。
项目源码及相关说明请查看此文:Spring Cloud入门教程-简介
上一篇博客讲了如何使用RestTemplate结合Ribbon 调用服务并实现负载均衡。这里要shuo说一下如何使用Feign来远程调度其他服务。
创建新的Moudel eureka-client-feign
pom.xml 如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.springcloud.demo</groupId>
<artifactId>springcloud-demo</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>eureka-client-feign</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>eureka-client-feign</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<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>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
添加配置与eureka-client-ribbon 相同,设置端口为8794
server.port=8794
spring.application.name=eureka-client-feign
eureka.client.service-url.defaultZone=http://localhost:8791/eureka/
在EurekaClientFeignApplication添加@EnableEurekaClient @EnableFeignClients注解
@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
@ComponentScan("com.springcloud.demo.eurekaclientfeign")
public class EurekaClientFeignApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientFeignApplication.class, args);
}
}
创建Feign 配置类 FeignConfig
@Configuration
public class FeignConfig {
@Bean
public Retryer feignRetryer() {
return new Retryer.Default(100, SECONDS.toMillis(1), 5);
}
}
注入Bean 后,Feign 在远程调用失败后hui会jing进行chng重试。
创建FeignService 接口实现feign Client
@FeignClient(value = "eureka-client", configuration = FeignConfig.class)
public interface FeignService {
@GetMapping("main")
int main();
}
注意:@FeignClient 声明一个Feign Client,
value 为远程调用服务名,
FeignConfig.class 配置类
main方法通过注解调用 eureka-client 的 "/main" 的API.
这里省略service 层,直接在controller中调用,创建controller:
@RestController
public class MainController {
@Autowired
FeignService feignService;
@GetMapping("main")
public int getMsg() {
return feignService.main();
}
}
启动eureka-server ,两个eureka-client 实例,启动eureka-feign ,请求http://localhost:8794/main
多次请求会交替出现8792,8793.