1. 配置服务注册功能
2. pom添加Feign依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
3. 编写远程调用接口
// 统一放在feign包下,这样一眼就看出这是远程调用接口
package com.atguigu.gulimall.member.feign;
import com.atguigu.common.utils.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
// 注解,表明调用注册中心中的哪一个服务
@FeignClient("gulimall-coupon")
public interface CouponFeignService {
// 具体调用哪一个uri
@RequestMapping("/coupon/coupon/member/list")
public R membercoupons();
}
4. 开启远程调用(启动类(配置类)中加注解)
@SpringBootApplication
// 开启远程调用功能,同时指定哪一个包下是远程调用接口
@EnableFeignClients(basePackages = "com.atguigu.gulimall.member.feign")
public class GulimallMemberApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallMemberApplication.class, args);
}
}
5. 通过远程调用接口调用远程服务
@RestController
@RequestMapping("member/member")
public class MemberController {
// 注入远程调用接口
@Autowired
CouponFeignService couponFeignService;
// 在里面调用远程服务
@RequestMapping("/coupons")
public R test() {
MemberEntity memberEntity = new MemberEntity();
memberEntity.setNickname("张三");
R membercoupons = couponFeignService.membercoupons();
return R.ok().put("member", memberEntity).put("coupons", membercoupons.get("coupons"));
}
}
6. Feign使用优化
6.1 Feign发起http请求,依赖于其他的框架,其底层客户端实现包括
- URLConnection:默认实现,不支持连接池
- Apache HttpClient:支持连接池
- OKHttp:支持连接池
6.2 优化方法
6.3 具体步骤
<!--httpClient的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
- 在项目的配置文件application.yml中添加连接池的配置
feign:
client:
config:
default: # default全局的配置
loggerLevel: BASIC # 日志级别,BASIC就是基本的请求和响应信息
httpclient:
enabled: true # 开启feign对HttpClient的支持
max-connections: 200 # 最大的连接数
max-connections-per-route: 50 # 每个路径的最大连接数