nacos服务治理总结
1、注解
<!--nacos 服务注册发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--OK http 的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
下面这两个依赖写在api的包下,其中loadbalancer写完了之后,它会自动配置 Spring Cloud LoadBalancer 的客户端负载均衡器,使得应用程序可以无缝地使用负载均衡功能。
<!--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>
2、com.twinkle.api.config
该文件夹下写OpenFeign配置类
import feign.Logger;
import org.springframework.context.annotation.Bean;
public class DefaultFeignConfig { // 千万不要在这个类上面加@Configuration注解,因为这个配置类会在其它启动类上的注解引用
@Bean
public Logger.Level feignLogLevel() {
return Logger.Level.BASIC; // 日志级别:NONE、BASIC、FULL、HEADERS
}
}
同时在启动类上注明@EnableFeignClients(basePackages = "com.twinkle.api.clients", defaultConfiguration = DefaultFeignConfig.class)
(启用OpenFeignClients,写明clients包所在目录,写明OpenFeign的配置类)
3、编写com.twinkle.api.clients
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Collection;
@FeignClient("cart-service")
public interface CartClient {
@DeleteMapping("/carts")
void deleteCartItemByIds(@RequestParam("ids") Collection<Long> ids); // 调用其它服务的controller层的方法
}
4、application.yaml
每个微服务下的application.yaml
server:
port: 8082
spring:
application:
name: twinkle-service
profiles:
active: dev
datasource:
url: jdbc:mysql://${hm.db.host}:3306/twinkle?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:
server-addr: 127.0.0.1:8848
feign:
okhttp:
enabled: true