springcloud integrates nacos to realize registration discovery center

Why do microservices need a service registration discovery center

  1. High availability: Nacos is a highly available registry that supports multi-node deployment and cluster mode, ensuring service stability and availability. When a node fails, other nodes can take over the functions of service registration and discovery to ensure the normal operation of the system.
  2. Dynamic configuration: Nacos can not only serve as a registration center, but also provide the function of a configuration center. After Spring Cloud integrates Nacos, it can realize dynamic configuration through Nacos and update configuration information in real time. The configuration can be dynamically adjusted without restarting the service, which improves the flexibility and maintainability of the system.
  3. Service discovery and load balancing: Nacos provides service registration and discovery functions, which can simplify calls and management between services. Through the Nacos registry, service providers can register themselves to the registry, and service consumers can obtain a list of available service instances from the registry and implement load balancing strategies. In this way, service invocation and expansion under the microservice architecture can be realized more conveniently.
  4. Health check: Nacos can periodically check whether the service instance in the registry is normal. Through the health check, faulty nodes can be automatically eliminated to ensure that service calls are only made to available nodes, which improves the stability and fault tolerance of the system.
  5. Management interface: Nacos provides a user-friendly management interface to view and manage service instance information, configuration information, and health status of the registry. Through the management interface, you can easily monitor and manage the services in the system, improving the efficiency of development and operation.

Spring Cloud integrates Nacos to implement the registration center, which can provide high availability, dynamic configuration, service discovery and load balancing, health check and other functions to help developers better manage and call services, and improve system maintainability and scalability.

How to use Registration Discovery Center

1. This example environment

JDK: 17

SpringBoot: 3.0.6

spring-cloud-starter-alibaba-nacos-config: 2021.0.4.0

nacos: 2.2.0-BATA

2. nacos installation

Refer to my previous article: Nacos startup and configuration

3.pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>springboot-nacos-discovery</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2021.0.4.0</version>
        </dependency>

    </dependencies>

4.application.yml

spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        group: DEFAULT_GROUP
        #指定文件名,没有则默认${spring.application.name}
        #指定文件后缀
        file-extension: yaml
        namespace: dca4fe79-6c62-44df-aa7f-12f58de7e05c #这里是nacos的命名空间的id
  config:
    import:
      - optional:nacos:${spring.application.name}.${spring.cloud.nacos.config.file-extension}

  application:
    name: nacos.cfg.test

server:
  port: 8080

5.NacosDiscoveryDemoController

@RestController
@RequestMapping("/distoryDemo")
public class NacosDiscoveryDemoController {

    @Autowired
    NacosDiscoveryService demoService;

    @GetMapping("hello")
    public Object echo(String name){
        return demoService.sayHello(name);
    }
}

6.ServerConfig

@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
    private int serverPort;

    public String getUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://" + address.getHostAddress() + ":" + this.serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }
}

7.NacosNacosDiscoveryServiceImpl

@Service
public class NacosNacosDiscoveryServiceImpl implements NacosDiscoveryService {

    @Autowired
    ServerConfig serverConfig;

    @Override
    public String sayHello(String name) {
        System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name +
                ", request from consumer: " + serverConfig.getUrl());
        return "Hello " + name + ", response from provider: " + serverConfig.getUrl();
    }

}

8. Start the test results with the http tool

image-20230716173203036

The entire example above is complete

If you need the complete source code, please pay attention to the official account "Architecture Palace", and reply "springcloud integrates nacos to realize registration discovery center" to get

write at the end

If you are interested in related articles, you can pay attention to the official account "Architecture Hall", and will continue to update AIGC, java basic interview questions, netty, spring boot, spring cloud and other series of articles, and a series of dry goods will be delivered at any time!

Guess you like

Origin blog.csdn.net/jinxinxin1314/article/details/131752870