一、服務(wù)注冊與發(fā)現(xiàn)場景
主要包含兩個服務(wù):
- zhshl-order服務(wù): 作為服務(wù)消費者
- zhsl-stock服務(wù): 作為服務(wù)提供者
當(dāng)我們啟用服務(wù)發(fā)現(xiàn)的時候,需要進行的操作主要有三步
0、前置條件,需要先搭建好一個nacas服務(wù),可以是一個集群或者是單個nacos服務(wù)??梢詤⒖糷ttps://nacos.io/zh-cn/docs/quick-start.html,
示例中使用需要使用nacos1.4.2版本匹配。具體配置關(guān)系可以參考:https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E
1、添加maven依賴
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2、配置服務(wù)提供者,將服務(wù)注冊到nacos中,后續(xù)通過
2.1 在bootstrap.yml的配置文件中配置nacos的地址
spring:
cloud:
nacos:
discovery:
service: zhshl-stock
server-addr: localhost:8848
server:
port: 8081
2.2 通過 Spring Cloud 原生注解 @EnableDiscoveryClient 開啟服務(wù)注冊發(fā)現(xiàn)功能:
@SpringBootApplication
@EnableDiscoveryClient
public class ZhslStockApplication {
public static void main(String[] args) {
SpringApplication.run(ZhslStockApplication.class, args);
}
}
@RestController
public class StockController {
@Value("${server.port}")
private String port;
@GetMapping("/stock/reduce/{productId}")
public String reduce(@PathVariable Integer productId) {
System.out.println("減庫存成功");
return "減庫存成功,響應(yīng)的是: " + port;
}
}
3、配置消費者,消費通過nacos的服務(wù)發(fā)現(xiàn)功能,從nacos中獲取到對應(yīng)的服務(wù)提供者的具體實例來進行調(diào)用
3.1、服務(wù)消費者對應(yīng)的配置信息:
spring:
cloud:
nacos:
discovery:
service: zhshl-stock
server-addr: localhost:8848
server:
port: 18082
3.2、 消費者的配置啟用服務(wù)發(fā)現(xiàn)
@SpringBootApplication
@EnableDiscoveryClient
public class ZhshlOrderApplication {
public static void main(String[] args) {
SpringApplication.run(ZhshlOrderApplication.class, args);
}
}
@Configuration
public class AppConfig {
@Autowired
private LoadBalancerClient loadBalancerClient;
@Bean
//@LoadBalanced
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(new LoadBalancerInterceptor(loadBalancerClient)));
return restTemplate;
}
}
@Slf4j
@RestController
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/order/create")
public String createOrder(Integer productId, Integer userId) {
String result = restTemplate.getForObject("http://zhshl-stock/stock/reduce/" + productId, String.class);
return "下單成功,庫存響應(yīng): " + result;
}
}
4、啟動服務(wù)提供者(zhsl-stock)和服務(wù)消費者(zhshl-order)
4.1、兩個服務(wù)啟動后,可以在nacos的控制平臺上看到如下信息
文章來源:http://www.zghlxwxcb.cn/news/detail-471231.html
4.2 在瀏覽器上輸入http://localhost:8082/order/create?productId=10,然后可以到如下的輸出:
下單成功,庫存響應(yīng): 減庫存成功,響應(yīng)的是: 18082
文章使用到的源碼請見:https://github.com/zhang1github2test/nacos-zhshl-parent/tree/master文章來源地址http://www.zghlxwxcb.cn/news/detail-471231.html
到了這里,關(guān)于Nacos作為服務(wù)注冊中心簡單示例的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!