SpringBoot整合Nacos

背景

Nacos作为阿里巴巴出版的服务配置与注册发现中心,使用起来十分方便,在国内也有大量的用户,今天我们结合Windows系统环境作为Nacos服务发布的载体,整合SpringBoot项目来使用Nacos

注:Linux部署Nacos也类似,具体可参考:

Docker 部署Nacos

Windows配置Nacos

下载Nacos安装包

Nacos 1.4.x

解压后,修改startup.cmd

在这里插入图片描述

set MODE = "standalone" # 设置Nacos单体启动

在这里插入图片描述

双击startup.cmd启动Nacos

这里表示启动成功

SpringBoot整合Nacos

SpringBoot版本

<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>

添加Nacos依赖

<!--NACOS-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.2.1.RELEASE</version>
</dependency>

设置yml配置文件

spring:
  profiles:
    active: dev
  application:
    name: test-nacos
  cloud:
    nacos:
      discovery:
        server-addr: 121.5.160.142:8848
      config:
        server-addr: 121.5.160.142:8848
        file-extension: yml
        group: DEFAULT_GROUP

  main:
    allow-bean-definition-overriding: true

management:
  endpoints:
    web:
      exposure:
        include: refresh,health

server-addr: 服务地址,这里部署在了服务器,如果是本地就写本地的IP地址即可
file-extension: 配置文件类型:properties或yml
group: nacos分组

注:需要添加application.yml和bootstrap.yml文件,内容一致,
因为bootstrap的优先级要比application高

在这里插入图片描述

Nacos中Data Id结构

dataid = application.name [ - profiles.active] . file-extension
eg. test-nacos-dev.yml

在这里插入图片描述

启动类中加Nacos注解

@EnableDiscoveryClient

在这里插入图片描述

代码

NacosConfig类

这里通过ConfigurableApplicationContext获取Spring的上下文信息,其中就包括从Nacos服务器获取的配置信息

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
@Data
@RefreshScope
public class NacosConfig {

    @Autowired
    private ConfigurableApplicationContext configurableApplicationContext;

    public String redisIp;

    public String getRedisIp() {
        return redisIp = configurableApplicationContext.getEnvironment()
        .getProperty(NacosConstants.redisIp);
    }

    public String redisPassword;

    public String getRedisPassword() {
        return redisPassword = configurableApplicationContext.getEnvironment()
        .getProperty(NacosConstants.redisPassword);
    }
}

Nacos常量

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

@Data
@Component
@NoArgsConstructor
public class NacosConstants {

    static String redisIp = "spring.redis.cache.nodes";

    static String redisPassword = "spring.redis.cache.password";

}

如果静态方法想要获取Nacos的配置信息怎么办呢?尝试过就应该知道,会发生获取不到配置信息的情况,因为静态方法的加载时间要比普通方法加载时间早,这时就要使用静态方法加载配置,下面是使用应用上下文将普通方法转静态方法的方法

静态访问方法工具类

import org.springframework.beans.BeansException;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
@RefreshScope
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) 
    throws BeansException {
        if (SpringContextUtil.applicationContext == null) {
            SpringContextUtil.applicationContext = applicationContext;
        }
    }
    
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String param) {

        return getApplicationContext().getBean(param);
    }

    public static <T> T getBean(Class<T> clazz) {
        T test=getApplicationContext().getBean(clazz);
        return test;
    }

    public static <T> T getBean(String param, Class<T> clazz) {
        return getApplicationContext().getBean(param, clazz);
    }
}

使用方式

在静态方法中通过静态访问方法工具类获取到配置信息即可

NacosConfig nacosConfig = SpringContextUtil.getBean(NacosConfig.class);

如下

@PostConstruct
private static void setJedisPoolConfig() {
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    NacosConfig nacosConfig = SpringContextUtil.getBean(NacosConfig.class);
    try {
        String val = nacosConfig.getRedisIp(); //直接获取配置对象的属性
        String password = nacosConfig.getRedisPassword(); //直接获取配置对象的属性
        String[] ipAndPort = val.split(":");
        pool = new JedisPool(config, StringUtils.trim(ipAndPort[0]), 
        Integer.parseInt(ipAndPort[1]), timeout, password, false);
    } catch (Exception e) {
        log.error("redis初始化异常:", e);
    }
}

总结

SpringBoot整合Nacos中要注意获取到的配置信息如果要在静态方法中使用的话,需要现将配置类转为静态配置类再使用

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

BirdMan98

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值