jasypt+springboot nacos @NacosValue动态刷新解决方案

159 阅读1分钟

配置

这个配置是 只要接收到这个事件 jasypt就会出发解密

jasypt:
  encryptor:
    password: 7YeeX6FtRfnagyMpZSrwRFzQN7UX1N
    refreshedEventClasses[0]: com.alibaba.nacos.spring.context.event.config.NacosConfigReceivedEvent

代码

@Component
@Slf4j
public class NacosConfigChangeListener implements ApplicationListener<NacosConfigReceivedEvent> {

    @Autowired
    private ConfigurableEnvironment environment;

    @NacosValue(value = "${testVaue:normal}", autoRefreshed = true)
    private String testValue;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private NacosValueAnnotationBeanPostProcessor nacosValueAnnotationBeanPostProcessor;
    //@Autowired
    private DefaultPropertyResolver defaultPropertyResolver;

    private RefreshScopeRefreshedEventListener refreshScopeRefreshedEventListener;


    @SneakyThrows
    @Override
    public void onApplicationEvent(NacosConfigReceivedEvent event) {
        ConfigService configService = event.getConfigService();
        String dataId = event.getDataId();
        String groupId = event.getGroupId();
        // 触发 刷新 @NacosValue 注解值
        nacosValueAnnotationBeanPostProcessor.onApplicationEvent(
                new NacosConfigReceivedEvent(configService, dataId, groupId, null, null));
    }


    @PostConstruct
    public void init() throws Exception {
        // wfEncryptorConfigurationProperties.setRefreshedEventClasses(Lists.newArrayList("com.alibaba.nacos.spring.context.event.config.NacosConfigReceivedEvent"));
        //refreshScopeRefreshedEventListener.afterPropertiesSet();
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 打印结果对比 是否刷新
                log.info(testValue + ",environment=" + environment.getProperty("testVaue", String.class));
            }
        }).start();
    }
}

下次出一个详细 jasypt的 和spring boot nacos 刷新原理流程