环境 springboot + springcloud
Nacos注册中心服务端
下载windows版或Linux版:https://nacos.io/zh-cn
目录结构:
配置文件./config/application.properties
启动文件./bin/startup.cmd
:
cmd命令启动单机服务startup.cmd -m standalone
父工程依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Service提供者
pom.xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
application.yml
spring:
application:
name: userservice
spring:
cloud:
nacos:
server-addr: http://localhost:8848
consumer消费者
(消费者也可以作为提供者身份出现)
pom.xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
application.yml
spring:
application:
name: orderservice
spring:
cloud:
nacos:
server-addr: http://localhost:8848
discovery:
cluster-name: SZ # 集群名称
OrderApplication
配置RestTemplate的Bean加入到Spring容器中
@MapperScan("cn.xxx.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
@LoadBalanced # 负责均衡 和 做拉取服务
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
OrderService
利用RestTemplate调用 UserService接口
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
Order order = orderMapper.findById(orderId);
// restTemplate.getForObject(请求地址, 返回值类型);
String url = "http://userservice/user/" + order.getUserId(); // userservice是提供者的spring.application.name
User user = restTemplate.getForObject(url, User.class);
order.setUser(user);
return order;
}
}
同集群优先的负载均衡
(NacosRule):默认的ZoneAvoidanceRule
并不能实现根据同集群优先来实现负载均衡。
application.xml
userservice:
ribbon:
NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule # Nacos负载均衡规则