头图
If you want to know more Nacos tutorials, welcome to star "on-nacos" open source project. Based on the introduction, principle, source code, and practical introduction of Nacos 2.x, it helps developers to quickly get started with Nacos.

This article introduces how to use Nacos in Spring Cloud projects. Nacos is mainly divided into two parts, configuration center and service registration and discovery. To use Nacos in a Spring Cloud project, you must first ensure that a Nacos service is started. For details, you can refer to " Getting Started with Nacos Quickly " to build a stand-alone Nacos service.

The source code for Nacos to access Spring Cloud can refer to the project spring-cloud-alibaba , and interested friends can view the source code. For the version correspondence of Spring Cloud Alibaba, please refer to: Release Notes Wiki

For the detailed code example of this article, click [nacos-spring-cloud] to view

Configuration Center

Create configuration

Open the console http://127.0.0.1:8848/nacos , enter the configuration management-configuration list, click the + sign to create a new configuration, and create a data source configuration example here: nacos-datasource.yaml

 spring:
    datasource:
     name: datasource
     url: jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull&useDynamicCharsetInfo=false&useSSL=false
     username: root
     password: root
     driverClassName: com.mysql.jdbc.Driver

https://tva1.sinaimg.cn/large/e6c9d24ely1h3kow3r2tkj21680u0wgu.jpg

add dependencies

After the configuration is created, you can view it in the console configuration management - configuration list. Next, I will demonstrate how to get the configuration information in Nacos in the Spring Cloud project.

The following dependencies need to be added to the project:

 <!--配置中心-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>${latest.version}</version>
</dependency>

If the Spring Boot version of the project is less than 2.4.0, you need to create bootstrap.properties in the project and then add some configuration of nacos to the bootstrap.properties file in the project:

 spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.name=nacos-datasource
spring.cloud.nacos.config.file-extension=yaml
spring.cloud.nacos.config.username=nacos
spring.cloud.nacos.config.password=nacos
Spring Boot version 2.4.0 does not start the bootstrap container by default. This project demonstrates how to use nacos in Spring boot < 2.4.0 version. If Spring Boot version ≥ 2.4.0, you can refer to ** Nacos Config 2.4.x Example for configuration

In Spring Cloud Alibaba, the splicing format of Nacos dataId is:

 ${prefix} - ${spring.profiles.active} . ${file-extension}
  • prefix 默认为 spring.application.name 的值,也可以通过配置项 @spring.cloud.nacos.config.prefix` to configure.
  • spring.profiles.active is the profile corresponding to the current environment. For details, please refer to the Spring Boot documentation

    Note that when the active profile is empty, the corresponding connector - will also not exist, and the splicing format of dataId becomes ${prefix} . ${file-extension}
  • file-extension is the data format of the configuration content, which can be configured through the configuration item spring.cloud.nacos.config.file-extension .

get configuration

@Value annotation to get configuration

 /**
 * @author lixiaoshuang
 */
@RestController
@RequestMapping(path = "springcloud/nacos/config")
public class AnnotationGetController {
    
    @Value(value = "${spring.datasource.name:}")
    private String name;
    
    @Value(value = "${spring.datasource.url:}")
    private String url;
    
    @Value(value = "${spring.datasource.username:}")
    private String username;
    
    @Value(value = "${spring.datasource.password:}")
    private String password;
    
    @Value(value = "${spring.datasource.driverClassName:}")
    private String driverClassName;
    
    @GetMapping(path = "annotation/get")
    private Map<String, String> getNacosDataSource2() {
        Map<String, String> result = new HashMap<>();
        result.put("name", name);
        result.put("url", url);
        result.put("username", username);
        result.put("password", password);
        result.put("driverClassName", driverClassName);
        return result;
    }
}

After starting the service, obtain configuration information by visiting http://localhost:8333/springcloud/nacos/config/annotation/get

https://tva1.sinaimg.cn/large/e6c9d24ely1h3lzju1ml3j21zq0hoadk.jpg

The @ConfigurationProperties annotation binds the configuration to the class

 /**
 * @author lixiaoshuang
 */
@Data
@ConfigurationProperties(prefix = "spring.datasource")
@Component
public class NacosDataSourceConfig {
    
    private String name;
    
    private String url;
    
    private String username;
    
    private String password;
    
    private String driverClassName;
}

/**
 * @author lixiaoshuang
 */
@RestController
@RequestMapping(path = "springcloud/nacos/config")
public class BindingClassController {
    
    @Resource
    private NacosDataSourceConfig nacosDataSourceConfig;
    
    
    @GetMapping(path = "binding/class/get")
    private Map<String, String> getNacosDataSource() {
        Map<String, String> result = new HashMap<>();
        result.put("name", nacosDataSourceConfig.getName());
        result.put("url", nacosDataSourceConfig.getUrl());
        result.put("username", nacosDataSourceConfig.getUsername());
        result.put("password", nacosDataSourceConfig.getPassword());
        result.put("driverClassName", nacosDataSourceConfig.getDriverClassName());
        return result;
    }
}

After starting the service, obtain configuration information by visiting http://localhost:8333/springcloud/nacos/config/binding/class/get

https://tva1.sinaimg.cn/large/e6c9d24ely1h3lzqevse3j21za0ey77u.jpg

Service Registration & Discovery

service registration

Add the following dependencies to the project:

 <!--注册中心-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>${latest.version}</version>
</dependency>

Then add some configuration of nacos to the application.properties file in the project:

 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.cloud.nacos.discovery.username=naocs
spring.cloud.nacos.discovery.password=nacos

When you see the following log after adding the configuration startup service, it means that the service registration is successful.

 nacos registry, DEFAULT_GROUP SPRING-CLOUD-CONFIG 192.168.1.8:8444 register finished

https://tva1.sinaimg.cn/large/e6c9d24ely1h3m1kf4qllj228v0u0naz.jpg

service discovery

Integrate @LoadBalanced RestTemplate

First simulate the interface of an order service, which can be called through service discovery

 /**
 * @author lixiaoshuang
 */
@RestController
public class OrderServiceController {
    
    @GetMapping("/order/{orderid}")
    public String echo(@PathVariable String orderid) {
        System.out.println("接到远程调用订单服务请求");
        return "[ORDER] : " + "订单id:[" + orderid + "] 的订单信息";
    }
}

First visit http://localhost:8444/order/1234 to get the order information with the order id 1234 and see if the interface can be adjusted:

https://tva1.sinaimg.cn/large/e6c9d24ely1h3m2ii2lp6j20yy07ydgc.jpg

Next, simulate a business interface and call the order interface. Here, RestTemplate has the capability of load balancing and service discovery by using the @LoadBalanced annotation, so that it can be called by specifying the service name.

 /**
 * @author lixiaoshuang
 */
@RestController
public class RestTemplateController {
    
    @Autowired
    public RestTemplate restTemplate;
    
    @Bean
    @LoadBalanced
    public RestTemplate RestTemplate() {
        return new RestTemplate();
    }
    
    @GetMapping("/call/order/{orderid}")
    public String callEcho(@PathVariable String orderid) {
        // 访问应用 SPRING-CLOUD-CONFIG 的 REST "/order/{orderid}"
        return restTemplate.getForObject("http://SPRING-CLOUD-CONFIG/order/" + orderid, String.class);
    }
}

Access the interface http://localhost:8444/call/order/1234 to get the order information of the order 1234. Internally, the service will be discovered through the service name SPRING-CLOUD-CONFIG, and the /order/{orderid} interface will be called to get the order information.

https://tva1.sinaimg.cn/large/e6c9d24ely1h3m2wozka4j20xi0akt98.jpg

Observe the log of the order service and find that there are logs of remote calls

https://tva1.sinaimg.cn/large/e6c9d24ely1h3m2xxo8wcj218c0hwmy7.jpg


晓双
76 声望15 粉丝

🏅Alibaba Nacos & Apache EventMesh Committer