Nacos 是阿里巴巴开源的一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。
Spring Cloud Nacos
优点: 1)开箱即用,适用于dubbo,spring cloud
2)AP模型,数据最终一致性
3)注册中心,配置中心二合一,提供控制台管理
4)纯国产,久经双十一考验
缺点: 1)刚刚开源不久,社区热度不够,依然存在bug
2)0.5.0 注册服务无鉴权认证机制,存在风险
0、服务容器负责启动,加载,运行服务提供者。
1、服务提供者在启动时,向注册中心注册自己提供的服务。
2、服务消费者在启动时,向注册中心订阅自己所需的服务。
3、注册中心返回服务提供者地址列表给消费者,如果有变更,注册中心将基于长连接推送变更数据给消费者。
4、服务消费者,从提供者地址列表中,基于软负载均衡算法,选一台提供者进行调用,如果调用失败,再选另一台调用。
5、服务消费者和提供者,在内存中累计调用次数和调用时间,定时每分钟发送一次统计数据到监控中心。
启动Nacos
- Linux/Unix/Mac 操作系统,执行命令
sh startup.sh -m standalone
- Windows 操作系统,执行命令
cmd startup.cmd
pom:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
yml配置:
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
application:
name: auth-server
服务调用:
@Autowired
private RestTemplate restTemplate;
String url = String.format("http://%s/uc/company/add/company?access_token=%s",
DiscoveryProvider.AUTH_SERVER, AccessTokenContextHolder.get());
Map res = restTemplate.postForObject(url, param, Map.class);
String url = String.format("http://%s/file/get/file?fileId={fileId}",
DiscoveryProvider.FILE_SERVER);
Map jsonObject = ·
restTemplate.getForObject(url,Map.class,ImmutableMap.of("fileId",fileId));
启动类:
package com.swy;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;
@ComponentScan(basePackages = {"com.*"})
@SpringCloudApplication
@DistributedTransaction
public class AuthServerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(AuthServerApplication.class, args);
// ServiceLocator locator = new ServiceLocator();
// locator.setApplicationContext(ctx);
}
}
自定义注解:
@Target({ElementType.TYPE})
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@EnableDistributedTransaction
@Import({DependenciesImportSelector.class})
public @interface DistributedTransaction {
boolean enabled() default true;
}