02.Nacos安装与应用
一、服务端安装
1.github上面搜索nacos
2.根据spring cloud alibaba组件版本关系,选择nacos版本下载
3.解压nacos,修改mode默认是集群修改为独立模式
4.配置文件位置,默认是内存方式保存,可以修改为数据库方式,也可以修改端口等。
5.运行,有地址信息,模式信息,信息保存位置信息
6.访问,默认用户名密码都是nacos
二、客户端配置
1.引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Spring-Cloud-Lry</artifactId>
<groupId>cn.luoruiyuan</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>stock</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- WEB场景 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
</project>
2.配置文件修改
server:
port: 8890
spring:
application:
#应用名称,也是nacos服务名称
name: order-service
cloud:
nacos:
discovery:
#登录用户名
username: nacos
#登录密码
password: nacos
#命名空间,根据环境进行设定(dev,uat,pro)
namespace: public
#服务器地址
server-addr: 127.0.0.1:8848
3.配置类
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author LRY
* @date 2022/7/3
*/
@Configuration
public class SpringCloudConfig {
@Bean
//nacos服务名称调用
@LoadBalanced
public RestTemplate restTemplate(RestTemplateBuilder builder){
RestTemplate build = builder.build();
return build;
}
}
4.订单服务调用库存服务
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author LRY
* @date 2022/7/2
*/
@RestController
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/order")
public String queryOrder(){
ResponseEntity<String> entity = restTemplate.getForEntity("http://stock-service/stock", String.class);
return "下单成功-----"+ entity.getBody().toString();
}
}
5.库存服务
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author LRY
* @date 2022/7/2
*/
@RestController
public class StockController {
@Value("${server.port}")
private String port;
@GetMapping("/stock")
public String queryOrder(){
return "减库存库存:"+port;
}
}
6.调用结果
赞(1)
赏