04-Nacos-服务注册基于spring boot实现

官方参考

在不依赖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);
    }
}
相关推荐
java1234_小锋1 天前
SpringBoot为什么要禁止循环依赖?
java·数据库·spring boot
ShiJiuD6668889991 天前
springboot基础篇
java·spring boot·spring
白宇横流学长2 天前
基于Spring Boot的校园考勤管理系统的设计与实现
java·spring boot·后端
_waylau2 天前
“Java+AI全栈工程师”问答02:Spring Boot 自动配置原理
java·开发语言·spring boot·后端·spring
i220818 Faiz Ul2 天前
高校教务|教务管理|基于springboot+vue的高校教务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·高校教务系统
贫民窟的勇敢爷们2 天前
SpringBoot多环境配置全解+配置优先级管控
java·spring boot·后端
霸道流氓气质2 天前
Spring @Scheduled 单线程陷阱:当设备重连阻塞了整个定时任务体系
java·spring boot·spring
欢璃2 天前
表白墙案例
java·开发语言·jvm·spring boot·spring·maven·mybatis
代码漫谈2 天前
Jetty vs Tomcat:Spring Boot应用场景最佳选择
spring boot·tomcat·jetty
贫民窟的勇敢爷们2 天前
SpringBoot整合MyBatis-Plus极致实战,高效实现数据库CRUD与分页条件查询
数据库·spring boot·mybatis