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;
}