目录
一、feign介绍
feign整合了ribbon和hystrix,不仅能进行远程调用,还具备了负载均衡,重试,降级和熔断的功能。提供了一种声明式的Web服务客户端定义的方式。
使用了我们所熟悉的spring mvc注解来对方法接口进行设置,拼接后台的服务访问路径和提交的参数。
二、feign的使用
1、feign远程调用
(1)创建项目
(2)编辑pom
添加eureka和feign依赖
<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>
(3)编辑yml
服务名称为:feign,使用端口:3001
spring:
application:
name: feign
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
(4)编辑主程序
添加@EnableFeignClient注解,开启Spring Cloud Feign的功能
package cn.tedu.sp09;
import ...;
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Sp09FeignApplication {
public static void main(String[] args) {
SpringApplication.run(Sp09FeignApplication.class, args);
}
}
(5)创建三个服务的Service层
分别添加@FeignClient("微服务名称"),并添加对应的方法,其中方法上使用@RequestMapping注解拼接路径以及参数
itemService
package cn.tedu.sp09.service;
import ...;
@FeignClient("item-service")
public interface ItemFeignService {
@GetMapping("/{orderId}")
JsonResult<List<Item>> getItems(@PathVariable String orderId);
@PostMapping("/decreaseNumber")
JsonResult decreaseNumber(@RequestBody List<Item> items);
}
userService
package cn.tedu.sp09.service;
import ...;
@FeignClient(name="user-service",fallback = UserFeignServiceFB.class)
public interface UserFeignService {
@GetMapping("/{userId}")
JsonResult<User> getUser(@PathVariable Integer userId);
// 拼接路径 /{userId}/score?score=新增积分
//注意,如果请求参数名与方法参数名不同,@RequestParam不能省略,并且要指定请求参数名:
//@RequestParam("score") Integer s
@GetMapping("/{userId}/score")
JsonResult addScore(@PathVariable Integer userId, @RequestParam Integer score);
}
orderService
package cn.tedu.sp09.service;
import ...;
@FeignClient(n