Nacos
Spring Boot微服务向Nacos注册
- pom
1 | <dependency> |
- Properties
1 | spring.application.name=microservice |
- 添加注解
1 |
|
临时实例和永久实例的区别
- 临时实例只是临时存在于注册中心中,会在服务下线或不可用时被注册中心剔除,临时实例主动向注册中心发送心跳包
- 永久实例在服务下线或不可用时也不会被注册中心剔除,注册中心会在永久服务初始化时根据客户端选择的协议类型(Http、TCP 以及 MySQL )注册探活的定时任务,注册中心主动向永久实例探活
Docker单机部署
1 | docker run -d --name nacos --restart=always \ |
Docker集群部署
- 创建网桥
1 | 创建名为bdg-nacos-cluster的网桥,在同一网桥下不同容器可以通过容器名称进行通信 |
- 创建MySQL容器,并初始化数据库nacos_config
1 | mkdir -p /etc/nacos-mysql/initdb |
- 创建Nacos节点
1 | 此处可根据节点名称更换,如nacos2、nacos3 |
SpringCloud LoadBalancer
SpringBoot微服务集成LoadBalancer
pom
1
2
3
4<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>添加注解
1 |
|
- 负载请求
1 |
|
负载方式
默认为RoundRobinLoadBalancer
轮询请求,如需更改负载方式如下操作
1 | // 注意此处不要添加@configuration |
1 | // 在启动端添加@LoadBalancerClients注解 |
缓存方案
- Springboot配置
1 | spring.cloud.loadbalancer.cache.enabled=true |
生命周期
1 |
|
OpenFeign
- 作用:动态组织远程发送的地址,但是实际负载均衡还是得靠LoadBalancer
- pom
1 | <dependency> |
- 添加注解,在
Application
类上添加@EnableFeignClients
- 声明接口
1 | "provider-service") (name = |
- 使用案例
1 |
|
使用优化细节
- 将默认的URLConnection替换为
OkHttpClient
或者HttpClient 5
1 | <dependency> |
1 | spring.cloud.openfeign.httpclient.hc5.enabled=true |
- OpenFeign请求/响应压缩,类似于nginx
1 | # 启用请求或响应GZIP压缩 压缩后带宽减小 服务器cpu上升 |
- 日志记录
1 |
|
1 | "provider-service",configuration = FeignConfiguration.class) (value = |
- @FeignClient转发到URL
1 | // 此时不会采用负载均衡 |
Dubbo3
服务提供者
- pom
1 | <dependency> |
- yaml
1 | server: |
- 添加注解
1 |
|
1 | // @DubboService注解可以将标注的服务实现类注册为Dubbo服务 |
1 | // 注意,需要依赖的DTO对象,必须实现序列化接口Serializable |
服务消费者
- pom
1 | <dependency> |
- yaml
1 | server: |
- 将服务提供者的接口复制过来(包名也得相同)
1 | public interface ProviderService { |
- 添加注解
1 |
|
1 |
|
Spring Cloud Gateway
- pom
1 | <dependency> |
- yaml
1 | spring: |