《深入理解Spring Cloud与微服务构建》学习笔记(十二)~写一个Feign客户端
一、在上一项目的基础上进行实现:新建一个eureka_feign module,在pom.xml添加eurekaClient和fign依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
同时添加application.yaml配置
spring:
application:
name: eureka-feign
server:
port: 8765
eureka:
client:
service-url:
defaultZone: http://localhost:8760/eureka
在启动类添加@EnableEurekaClient 和 @EnableFeignClients 两个注解,于是就开启了EurekaClient 和 FeignClient功能
二、此时该程序已经具备了Feign功能,我们需要先建立一个FeignConfig配置类:添加@Configuration表明该类是一个配置类,并注入一个beanName为feignRetryer的Retryer的Bean,注入该bean后,远程服务调用失败后,会进行重新尝试。
@Configuration
public class FeighConfig {
@Bean
public Retryer FeignRetryer(){
return new Retryer.Default(100,SECONDS.toMillis(1),5);
}
}
再建立一个EurekaClientFeign接口,注解@FeignClient 声明为Feign Client,添加value远程调用服务,添加一个方法调用远程服务的接口:
//这里声明调用eureka-lient远程服务
@FeignClient(value = "eureka-client",configuration = FeighConfig.class)
public interface EurekaClientFeign {
//这里声明为调用eureka-client的hello远程服务
@GetMapping(value = "/hello")
String sayHiFromFeignClient();
}
在service层建立HiService服务,注入EurekaClientFeign的Bean,通过EurekaClientFeign调用syaHiFromFeignClient方法实现远程调用:
@Service
public class HiService {
@Autowired
EurekaClientFeign eurekaClientFeign;
public String sayHi(){
return eurekaClientFeign.sayHiFromFeignClient();
}
}
这里代码报了一个错,没解决掉,但是可以忽略,可以正常启动。
建立一个Controller类,开启RestController功能,写一个接口hi,在该接口调泳HiService的SayHi方法,sayHi方法通过EurekaClientFeign远程调用eureka-client的API接口"hello"。:
@RestController
public class HiController {
@Autowired
HiService hiService ;
@GetMapping("/hi")
public String hi(){
return hiService.sayHi();
}
}
此时启动应用,在浏览器访问:http://localhost:8765/hi
多次刷新可以看到已经可以成功调用到了eureka-client的两个实例的接口,到此我们也就实现了Feign客户端的远程接口调用。
示例代码:https://download.****.net/download/ssdate/11011264