springcloud学习记录-feign
feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。
在前面博客中使用RestTemplate进行springcloud子模块之间的通信。
现在学习使用feign来完成。
项目搭建
还是可以在之前Eureka-client-consumer的基础上进行修改。但是这里从新建开始
1.新建module:client_consumer_feign,新建时勾选openfeign的依赖。pom.xml依赖如下:
<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>
2.在启动类上添加注解:@EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ClientConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ClientConsumerFeignApplication.class, args);
}
}
3.yml配置文件
server:
port: 8014
spring:
application:
name: client-consumer-feign
eureka:
client:
serviceUrl:
defaultZone: http://eureka1:8761/eureka/,http://eureka2:8762/eureka/,http://eureka3:8763/eureka/
feign:
hystrix: #开启hystrix
enabled: true
hystrix:
command:
defalut:
# IFeign#getBudget(String):
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 3000
# 滚动窗口
metrics:
rollingStats:
timeInMilliseconds: 3000
circuitBreaker:
requestVolumeThreshold: 2
errorThresholdPercentage: 50
sleepWindowInMilliseconds: 3000
threadpool:
default:
coreSize: 20
# IFeign#getBudget(String):
# coreSize: 10
# IFeign#getOrder(String):
# coreSize: 10
4.写一个接口
//eureka-client-provider表示访问哪个服务
@FeignClient(name = "eureka-client-provider",fallback = CallBackMethod.class)
public interface IFeign {
@GetMapping("/hiya") //对应于provider方的controller路径(前面博客写的)
String getBudget(@RequestParam("message") String message); //方法名是任意的:getBudget()
}
5.回调类
@Component
public class CallBackMethod implements IFeign {
@Override
public String getBudget(String message) {
return "message为"+message+"的用户,暂时没有找到优惠券哦~~";
}
}
5.在controller中简单测试
@RestController
public class ribbonController {
// @Autowired
// private RestTemplate restTemplate;
/**
* 以前是使用RestTemplate来进行交流的,现在换为feign进行操作
*/
@Autowired
private IFeign feignya;
@GetMapping("/hi")
public String sayHi(@RequestParam("message") String message){
String budget = feignya.getBudget( message);
return budget;
// return restTemplate.getForObject("http://eureka-client-provider/hi?message={1}" , String.class,message); //以前使用RestTemplate 时的访问方式
}
}
目录结构如下:
启动后访问:http://localhost:8014/hi?message=1进行测试