注:原文飞书链接:牛
1.引入依赖
服务发现者、注册者都需要nacos
<!--nacos 服务注册发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
openFeign和负载均衡放在公共模块的pom
<!--openFeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--负载均衡器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
发现者引入公共模块的依赖,另外对于连接池使用Ok http方式,也在发现者引用
//举例
<dependency>
<groupId>com.heima</groupId>
<artifactId>hm-api</artifactId>
<version>1.0.0</version>
</dependency>
<!--OK http 的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
2.添加配置
spring:
application:
name: item-service # 服务名称
cloud:
nacos:
server-addr: 192.168.150.101:8848 # nacos地址
3.在虚拟机中导入nacos的数据库、镜像文件
4.使用docker创建容器,防火墙开放端口(8848,可以改但是另外两个端口的是这个端口的1000和1001偏移量)
docker run -d \
--name nacos \
--env-file ./nacos/custom.env \
-p 8848:8848 \
-p 9848:9848 \
-p 9849:9849 \
--restart=always \
nacos/nacos-server:v2.1.0-slim
5.在发现服务启动类添加@EnableFeignClients注解
basePackages 为公共模块下client接口包名,为了防止SpringBoot扫描不到这个包
@EnableFeignClients(basePackages = "com.hmall.api.client")
6.在公共模块创建Feign接口
@FeignClient("item-service")//参数值:配置文件的服务名称
public interface ItemClient {
@GetMapping("/items")//远程调用接口的请求方式,url
//ItemDTO远程调用的返回值类型 ,Collection<Long> ids传递的参数
List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
}
7.在发现者的service引入创建的接口
@Autowired
private ItemClient itemClient;
8.发现者service调用接口方法
List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
if(CollUtils.isEmpty(items)){
return;
}
9.日志级别
当openFeign所在的包的日志级别为debug时,才能配置日志级别
logging:
level:
com.hmall: debug
创建一个公共模块配置类,并且创建一个Bean
public class DefaultFeignConfig {
@Bean
public Logger.Level feignLogLevel(){
return Logger.Level.FULL;
}
}
在启动类注解上加入defaultConfiguration = DefaultFeignConfig.class,DefaultFeignConfig为配置类字节码
@EnableFeignClients(basePackages = "com.hmall.api.client" ,defaultConfiguration = DefaultFeignConfig.class)