nacos使用

1、定义

Nacos 是一个更易于帮助构建云原生应用的动态服务发现、配置和服务管理平台,提供注册中心、配置中心和动态 DNS 服务三大功能。能够无缝对接Springcloud、Spring、Dubbo等流行框架。

2、作用

服务注册以及健康检查

动态DNS、权重路由、负载均衡

动态配置

服务及运元数据管理

3、基本原理

服务注册

配置中心

官方文档

4、启动

下载启动

截屏2022-04-13 14.35.51

5、服务注册

样例代码

public class NamingExample {

    public static void main(String[] args) throws NacosException {

        Properties properties = new Properties();
        properties.setProperty("serverAddr", System.getProperty("serverAddr"));
        properties.setProperty("namespace", System.getProperty("namespace"));

        NamingService naming = NamingFactory.createNamingService(properties);

        naming.registerInstance("sever", "11.11.11.11", 8888, "TEST1");

        naming.registerInstance("sever", "2.2.2.2", 9999, "DEFAULT");

        System.out.println(naming.getAllInstances("sever"));

        naming.deregisterInstance("sever", "2.2.2.2", 9999, "DEFAULT");

        System.out.println(naming.getAllInstances("sever"));

        naming.subscribe("sever", new EventListener() {
            @Override
            public void onEvent(Event event) {
                System.out.println(((NamingEvent) event).getServiceName());
                System.out.println(((NamingEvent) event).getInstances());
            }
        });
    }
}

springboot集成

                <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>0.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-discovery-spring-boot-starter</artifactId>
            <version>0.2.1</version>
        </dependency>
        <!--不加这个api启动会报错-->
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>0.6.2</version>
        </dependency>
spring:
  application:
    name: sever
  profiles:
    active: dev
nacos:
  config:
    server-addr: 127.0.0.1:8848
  discovery:
    server-addr: 127.0.0.1:8848
server:
  port: 8081
@SpringBootApplication
@Controller
public class Server1Application {

    @NacosInjected
    private NamingService namingService;

    @Value("${server.port}")
    private int serverPort;

    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 手动上报
     *
     * @throws NacosException
     */
    @PostConstruct
    public void registerInstance() throws NacosException {
        namingService.registerInstance(applicationName, "127.0.0.1", serverPort);
    }

    public static void main(String[] args) {
        SpringApplication.run(Server1Application.class, args);
    }

    @GetMapping("/get")
    @ResponseBody
    public String get(String serviceName) {
        try {
            List<Instance> allInstances = namingService.getAllInstances(serviceName);
            return JSON.toJSONString(allInstances);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return "";
    }

}

截屏2022-04-13 14.52.22

配合springcloud @EnableDiscoveryClient 注解可以开启自动服务注册

动态配置

样例代码

public class ConfigExample {

    public static void main(String[] args) throws NacosException, InterruptedException {
        String serverAddr = "localhost";
        String dataId = "example";
        String group = "DEFAULT_GROUP";
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("recieve:" + configInfo);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });

        boolean isPublishOk = configService.publishConfig(dataId, group, "nacos.config.test.name");
        System.out.println(isPublishOk);

        Thread.sleep(3000);
        content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);

        boolean isRemoveOk = configService.removeConfig(dataId, group);
        System.out.println(isRemoveOk);
        Thread.sleep(3000);

        content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        Thread.sleep(300000);

    }
}

springboot继承

指定dataid和group(默认default_group)

@SpringBootApplication
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class ConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigApplication.class, args);
    }

}
@RestController
public class NacosConfigController {

    @NacosValue(value = "${nacos.config.test.name:11111}", autoRefreshed = true)
    private String testName;

    @GetMapping(value = "/get")
    public String get() {
        return testName;
    }
}

截屏2022-04-13 14.44.07

nacos控制台修改,再次调用会发现值已修改

results matching ""

    No results matching ""