Springcloud、Springmvc+Nacos注册中心实现服务注册

目录

背景

实现

Nacos环境搭建

Springcloud服务注册

Maven配置

代码实现

Springmvc服务注册

Maven依赖

代码实现 


背景

不管是springcloud还是springmvc实现服务的自动注册,都是在项目启动完成bean初始化时,调用nacos服务的API,实现的自动注册。

实现

Nacos环境搭建

官网:什么是 Nacos

SpringCloud集成文档:Nacos Spring Cloud 快速开始 

Spring集成文档:Nacos Spring 快速开始

参考之前写的博文:Springcloud+Druid+Mybatis+Seata+Nacos动态切换多数据源,分布式事务的实现

使用的nacos版本1.4.1 

Springcloud服务注册

Maven配置

用到了nacosdiscovery和lombok

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

 代码实现

package com.luck.config;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;

import lombok.Data;

@Configuration
public class NacosDiscoveryConfig implements SmartInitializingSingleton, ApplicationListener<ContextClosedEvent> {

	@Value("${spring.cloud.nacos.discovery.namespace}")
	String namespace;

	@Value("${spring.cloud.nacos.discovery.server-addr}")
	String serverAddr;

	@Data
	@Component
	@ConfigurationProperties("luck.nacos.server")
	class NacosServerProperties {

		/** 服务IP地址 */
		private String ip = "0.0.0.0";
		/** 服务端口号 */
		private Integer port = 8080;
		/** 服务名称 */
		private String serviceName = "cloud-luckserver";

		@Autowired
		InetUtils inetUtils;

		public void setIp(String ip) {
			if (ip != null)
				this.ip = ip.trim();
		}

		public String getFirstIp() {
			if ("0.0.0.0".equals(ip))
				return inetUtils.findFirstNonLoopbackAddress().getHostAddress();
			return ip;
		}
	}

	@Autowired
	NacosServerProperties nacosServerProperties;

	/** 服务注册 */
	@Autowired
	NacosServiceRegistry nacosServiceRegistry;

	@Autowired
	ApplicationContext context;

	NacosRegistration registration;

	@Override
	public void afterSingletonsInstantiated() {

		NacosDiscoveryProperties properties = new NacosDiscoveryProperties();
		properties.setNamespace(namespace);
		properties.setPort(nacosServerProperties.getPort());
		properties.setIp(nacosServerProperties.getFirstIp());
		properties.setServerAddr(serverAddr);
		properties.setService(nacosServerProperties.getServiceName());

		registration = new NacosRegistration(properties, context);

		registration.setPort(nacosServerProperties.getPort());
		nacosServiceRegistry.register(registration);

	}

	@Override
	public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
		nacosServiceRegistry.deregister(registration);
	}
}

Springmvc服务注册

Maven依赖

用到了nacos-spring-context和hutool

<dependency>
    <groupId>com.alibaba.nacos</groupId>
    <artifactId>nacos-spring-context</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.1.19</version>
</dependency>

代码实现 

package com.luck.config.nacos;

import java.util.Properties;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.luck.utils.Constant;

import cn.hutool.core.util.NetUtil;

@Configuration
public class NacosDiscoveryConfig implements SmartInitializingSingleton, ApplicationListener<ContextClosedEvent> {

	private String namespace = Constant.getProperty("nacos.naming.namespace", "default");
	private String serverAddr = Constant.getProperty("nacos.naming.server-addr", null);
	private String group = Constant.getProperty("nacos.naming.group", "DEFAULT");
	private String ip = NetUtil.getLocalhostStr();
	private Integer port = Integer.parseInt(Constant.getProperty("server.port", "8080"));
	private String serviceName = Constant.getProperty("nacos.server.name", "cloud-luckserver");

	/** 服务注册 */
	private NamingService namingService;

	@Override
	public void afterSingletonsInstantiated() {
		if (null != namingService || null == serverAddr) {
			return;
		}

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

		try {
			namingService = NamingFactory.createNamingService(properties);
			namingService.registerInstance(serviceName, ip, port, group);
		} catch (NacosException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
		if (null == namingService) {
			return;
		}
		try {
			namingService.deregisterInstance(serviceName, ip, port, group);
		} catch (NacosException e) {
			e.printStackTrace();
		}
	}
}

需要注意这个配置类要可以被spring扫描到,如在xml添加

<context:component-scan base-package="com.luck.config.nacos" />

猜你喜欢

转载自blog.csdn.net/anshichuxuezhe/article/details/125842426