注册中心
三个角色
- 服务提供者:是指提供可复用和可调用服务的应用方。
- 服务消费者:是指会发起对某个服务调用的应用方。
- 注册中心:记录并监控微服务的实例状态,推送服务变更信息
Nacos搭建
参考自Nacos官方文档
三种部署模式:
- 单机部署:用于测试
- 集群模式:用于生产场景
- 多集群模式:用于多数据场景
单机部署Nacos
startup.cmd -m standalone
服务注册
- 导入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
- 配置文件导入
spring:
cloud:
nacos:
discovery:
server-addr: ${NACOS_SERVER_ADDR:127.0.0.1:8848} # Nacos服务器地址
namespace: ${NAMESPACE:} # 可选,命名空间ID
group: ${GROUP:DEFAULT_GROUP} # 服务分组,默认为DEFAULT_GROUP
config:
server-addr: ${NACOS_SERVER_ADDR:127.0.0.1:8848} # 如果同时使用配置中心,地址应与发现一致
file-extension: yaml # 配置文件格式,默认为properties
namespace: ${NAMESPACE:} # 同上,命名空间ID
或者,如果你使用的是application.properties:
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
服务发现与负载均衡
使用OpenFeign调用服务
-
引入OpenFeign
<!--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>
-
开启OpenFeign客户端
@SpringBootApplication @EnableFeignClients // 如果Feign客户端不在同一包下,可以指定basePackages属性 public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } }
-
定义Feign客户端接口
@FeignClient(name = "service-producer") public interface ProducerClient { @GetMapping("/api/hello") String hello(); }
-
使用Feign客户端(就像调用方法一样)
@RestController public class ConsumerController { @Autowired private ProducerClient producerClient; @GetMapping("/consumer/hello") public String consumerHello() { String response = producerClient.hello(); return "Consumer says: " + response; } }
使用连接池
# application.yml
spring:
cloud:
openfeign:
okhttp:
enabled: true # 启用OkHttp作为Feign的客户端