Nacos
1、注册中心基本概念
2、配置nacos
在需要使用nacos的项目中的application.yaml配置nacos<!--nacos 服务注册发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
(下面代码最后四行是重点)
server:
port: 8081
spring:
application:
name: item-service # 微服务名称
profiles:
active: dev
datasource:
url: jdbc:mysql://${hm.db.host}:3306/hm-item?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: ${hm.db.pw}
cloud:
nacos:
discovery:
server-addr: 47.97.62.142:8848
3、创建OpenFeign
两个依赖:<!--openFeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--负载均衡器(早期使用Ribbon,现在使用loadbalancer)-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
紧接着需要在启动类上加上@EnableFeignClients
的注解,然后在src下的client包中,定义一个新的接口,编写Feign客户端:
package com.hmall.cart.client;
import com.hmall.cart.domain.dto.ItemDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Collection;
import java.util.List;
@FeignClient("item-service")
public interface ItemClient {
@GetMapping("/items")
List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
// @RequestParam("ids")效果是把“?ids=”拼接到url的路径中,然后再通过该url向注册服务中心发送请求
}
4、在具体的业务中调用nacos注册中心的服务
private final ItemClient itemClient;
List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
if (CollUtils.isEmpty(items)) {
throw new BadRequestException("购物车中的商品不存在");
}
5、优化
Feign底层是通过HttpURLConnection(不支持连接池)发起的http请求,为了减少频繁连接和断开连接的开销,需要使用OpenFeign连接池
依赖:
<!--OK http 的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
application.yaml的配置:
<!--OK http 的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>