在上一篇部落格中介紹了nacos作為配置設定配置中心傳送門。本篇将nacos作為服務注冊中進行介紹
前提條件是你可以連上nacos服務。操作步驟建nacos官方入門手冊
服務發現
1.添加maven依賴
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
注意一點:選擇nacos的版本需要根據你的springboot版本号來決定
更多的詳細的版本對應關系檢視官網傳送門
2.在 bootstrap.properties 或者 bootstrap.yml中配置 Nacos server 的位址和應用名
bootstrap.properties 中添加
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.application.name=example
bootstrap.yml 添加
spring:
application:
name: nacos-config-example
profiles:
active: test
cloud:
nacos:
discovery:
server-addr: http://127.0.0.1:8848
3.在啟動類中通過 Spring Cloud 原生注解 @EnableDiscoveryClient 開啟服務注冊發現功能:
@EnableDiscoveryClient
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.example.demo;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* @author sz
* @version V1.0
* @Description: 測試nacos作為分布式配置中心(用一句話描述該檔案做什麼)
* @date 2020-11-18
*/
@RefreshScope
@RestController
public class TestController {
@Value("${user.name}")
String userName;
@Value("${user.age}")
int age;
@RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
public String echo(@PathVariable String string) {
System.out.println("請求進來了");
return "Hello Nacos Discovery " + string;
}
@RequestMapping("/user")
public String simple() {
return "Hello Nacos Config!" + "Hello " + userName + " " + age + " [UserConfig]: ";
}
// @SentinelResource("resource")
@RequestMapping("/test")
public String test() {
return "test";
}
@SentinelResource("resource")
@RequestMapping("/hello")
public String hello() {
return "Hello";
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int i=0;
initFlowRules();
while (true) {
Entry entry = null;
try {
i++;
entry = SphU.entry("HelloWorld");
/*您的業務邏輯 - 開始*/
System.out.println("hello world");
long tmp = System.currentTimeMillis();
if (tmp-startTime >1000){
System.out.println("執行了"+i+"次");
break;
}
/*您的業務邏輯 - 結束*/
} catch (BlockException e1) {
/*流控邏輯處理 - 開始*/
System.out.println("block!");
/*流控邏輯處理 - 結束*/
} finally {
if (entry != null) {
entry.exit();
}
}
}
}
private static void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("HelloWorld");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
// Set limit QPS to 20.
rule.setCount(20);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
}
4.配置服務消費者,進而服務消費者可以通過 Nacos 的服務注冊發現功能從 Nacos server 上擷取到它要調用的服務。也是在bootstrap.properties 或者 bootstrap.yml配置
注意是另外一個服務
spring:
application:
name: hamal-manage
cloud:
nacos:
config:
server-addr: http://127.0.0.1:8848
file-extension: properties
group: DEFAULT_GROUP
5.通過 Spring Cloud 原生注解 @EnableDiscoveryClient 開啟服務注冊發現功能。給 RestTemplate 執行個體添加 @LoadBalanced 注解,開啟 @LoadBalanced 與 Ribbon 的內建:
@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerApplication {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(NacosConsumerApplication.class, args);
}
@RestController
public class TestController {
private final RestTemplate restTemplate;
@Autowired
public TestController(RestTemplate restTemplate) {this.restTemplate = restTemplate;}
@RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
public String echo(@PathVariable String str) {
return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
}
}
}
6.啟動NacosConsumerApplication 和DemoApplication 這兩個服務通路
http://localhost:8080/echo/2018,傳回内容為 Hello Nacos Discovery 2018,并且在DemoApplication 的控制台列印出來請求進來了