Nacos使用(中):Java项目和Spring项目使用Nacos

Nacos使用(上):Nacos安装
Nacos使用(中):Java项目和Spring项目使用Nacos
Nacos使用(下):SpringBoot和SpringCloud项目中使用Nacos

3.使用Nacos

3.1 java SDK

引入jar包

<dependency>
  <groupId>com.alibaba.nacos</groupId>
  <artifactId>nacos-client</artifactId>
  <version>2.2.0</version>
</dependency>
<dependency>
  <groupId>com.alibaba.nacos</groupId>
  <artifactId>nacos-common</artifactId>
  <version>2.2.0</version>
</dependency>

3.1.1 配置中心

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author 专治八阿哥的孟老师
 */
public class ConfigExample {
    public static void main(String[] args) throws NacosException, InterruptedException, IOException {
        String serverAddr = "localhost";
        String dataId = "application-dev.properties";
        String group = "DEFAULT_GROUP";
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);

        properties.put(PropertyKeyConst.USERNAME, "nacos");
        properties.put(PropertyKeyConst.PASSWORD, "nacos");
        properties.put(PropertyKeyConst.NAMESPACE, "dev");
        // 查询配置
        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;
            }
        });
        // 发布配置,注意会覆盖原来的配置
        System.out.println("发布新配置");
        boolean isPublishOk = configService.publishConfig(dataId, group, "content");
        System.out.println(isPublishOk);

        Thread.sleep(3000);
        // 查询新的配置
        System.out.println("查询新配置");
        content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        // 删除配置
        System.out.println("删除配置");
        boolean isRemoveOk = configService.removeConfig(dataId, group);
        System.out.println(isRemoveOk);
        Thread.sleep(3000);
        System.out.println("再次查询新配置");
        content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        Thread.sleep(300000);
    }
}

3.1.2 服务治理

服务注册

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;

import java.io.IOException;
import java.util.Properties;

/**
 * @author 专治八阿哥的孟老师
 */
public class AppRegister {
    public static void main(String[] args) throws NacosException, IOException, InterruptedException {
        Properties properties = new Properties();
        // 多个地址使用逗号隔开
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
        properties.setProperty(PropertyKeyConst.NAMESPACE, "dev");
        properties.put(PropertyKeyConst.USERNAME, "nacos");
        properties.put(PropertyKeyConst.PASSWORD, "nacos");
        NamingService naming = NamingFactory.createNamingService(properties);
        // 注册到注册中心, 默认groupName=DEFAULT_GROUP
        naming.registerInstance("app1", "11.11.11.11", 8888);
        naming.registerInstance("app2", "2.2.2.2", 9999);
        Thread.sleep(1000);
        System.out.println(naming.getAllInstances("app1"));
        System.out.println(naming.getAllInstances("app2"));
        System.in.read();
    }
}

在这里插入图片描述

服务订阅

import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.AbstractEventListener;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.NamingEvent;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 专治八阿哥的孟老师
 */
public class AppSubscribe {
    public static void main(String[] args) throws NacosException, InterruptedException, IOException {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
        properties.setProperty(PropertyKeyConst.NAMESPACE, "dev");
        properties.put(PropertyKeyConst.USERNAME, "nacos");
        properties.put(PropertyKeyConst.PASSWORD, "nacos");
        NamingService naming = NamingFactory.createNamingService(properties);
        naming.registerInstance("app1", "55.55.55.55", 8080);
        System.out.println("instances after register: " + naming.getAllInstances("app1"));

        Executor executor =
            new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), runnable -> {
                Thread thread = new Thread(runnable);
                thread.setName("test-thread");
                return thread;
            });

        // 订阅服务名为app1, 当app1的实例数量发生变化, 会收到回调
        naming.subscribe("app1", new AbstractEventListener() {
            @Override
            public Executor getExecutor() {
                return executor;
            }

            @Override
            public void onEvent(Event event) {
                System.out.println("serviceName: " + ((NamingEvent)event).getServiceName());
                System.out.println("instances from event: " + ((NamingEvent)event).getInstances());
            }
        });

        System.in.read();
    }
}

在这里插入图片描述

3.2 Spring SDK

在这里插入图片描述

引入jar包

<dependency>
  <groupId>com.alibaba.nacos</groupId>
  <artifactId>nacos-spring-context</artifactId>
  <version>1.1.1</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.2.13.RELEASE</version>
</dependency>

spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

    <context:component-scan base-package="config"/>
</beans>

application.properties

nacos.server-addr=127.0.0.1:8848
nacos.namespace=dev
nacos.username=nacos
nacos.password=nacos

配置类

package config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.spring.context.annotation.EnableNacos;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;

/**
 * @author 专治八阿哥的孟老师
 */
@Configuration
@PropertySource("classpath:application.properties")
@EnableNacos(
    globalProperties = @NacosProperties(serverAddr = "${nacos.server-addr}", username = "${nacos.username}", password = "${nacos.password}"))
//读取指定配置文件
@NacosPropertySource(dataId = "example.properties", groupId = "DEFAULT_GROUP", autoRefreshed = true)
public class NacosConfiguration {

}

配置中心和服务治理

package config;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Component;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.AbstractEventListener;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.NamingEvent;

/**
 * @author 专治八阿哥的孟老师
 */
@Component
public class TestBean {
    // 读取配置文件中的属性
    @NacosValue(value = "${test.config}", autoRefreshed = true)
    private String config;
    // 配置中心
    @NacosInjected
    private ConfigService configService;
    // 服务订阅和发布
    @NacosInjected
    private NamingService namingService;

    public void test() {
        System.out.println(config);
    }

    public void publish() throws NacosException {
        System.out.println("发布新配置");
        boolean isPublishOk = configService.publishConfig("example.properties", "DEFAULT_GROUP", "test.config=efg");
    }

    public void service() throws NacosException {
        namingService.registerInstance("app1", "55.55.55.55", 8080);
        Executor executor =
            new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), runnable -> {
                Thread thread = new Thread(runnable);
                thread.setName("test-thread");
                return thread;
            });
        // 订阅服务名为app1, 当app1的实例数量发生变化, 会收到回调
        namingService.subscribe("app1", new AbstractEventListener() {
            @Override
            public Executor getExecutor() {
                return executor;
            }

            @Override
            public void onEvent(Event event) {
                System.out.println("serviceName: " + ((NamingEvent)event).getServiceName());
                System.out.println("instances from event: " + ((NamingEvent)event).getInstances());
            }
        });

    }
}

测试类

package config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author 专治八阿哥的孟老师
 */
public class ConfigTest {
    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        TestBean bean = context.getBean(TestBean.class);
        // bean.test();
        // bean.publish();
        bean.service();
        System.in.read();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专治八阿哥的孟老师

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值