在不依赖spring cloud 组件基础上,单独的微服务项目,实现nacos接入
1、依赖文件pom.xml
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.11</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.11</version>
</dependency>
2、配置参数bootstrap.yml
# 项目自身配置
server:
port: 8081
ip: 192.168.20.150
name: MOOD-SERVICE
# nacos注册配置
nacos:
discovery:
server-addr: 169.254.100.102:8848
config:
auto-refresh: true
server-addr: 169.254.100.102:8848
3、NacosConfig
使用NamingService添加nacos配置信息
/***
*
* @author xuancg
* @date 2023/2/7
*/
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
@NacosPropertySource(dataId = "nacos-springboot-service", autoRefreshed = true)
public class NacosConfig {
@Value("${server.port}")
private int serverPort;
@Value("${server.ip}")
private String ip;
@Value("${server.name}")
private String applicationName;
@NacosInjected
private NamingService namingService;
/**
* 开机自动注册服务
*
* @throws NacosException
*/
@PostConstruct
public void registerInstance() throws NacosException {
namingService.registerInstance(applicationName, ip, serverPort);
}
}