(十二) 记一次spring refreshScope 的使用

本文介绍如何在Spring Boot应用中使用@RefreshScope注解和Actuator端点实现缓存的动态刷新,通过实例演示了当数据库表更新时,如何通过发送HTTP POST请求到/actuator/refresh来触发缓存重新加载,避免了重启应用即可更新缓存数据。

十二. 记一次spring refreshScope 的使用

引子

项目缓存里面的值,使用频率不高,就不设置过期时间了.希望手动发送一个请求给spring boot 之后相对应的缓存就更新了.

*/在生产中有一张codeMapping表,其中的数据在程序启动时就加载进去.程序运行中访问缓存里面的数据.
表更新以后,发个

➜  ~ curl -X POST http://localhost:8080/actuator/refresh

缓存就会重新加载数据库中的数据
/*

yml配置

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

default 值: health.info

代码

interface CodeMapper {

    fun getValue(type: String, key: String): String?
}

@Component
@RefreshScope
internal class CodeMappingService(jdbcTemplate: JdbcTemplate) : CodeMapper {

    private val logger: Logger = LogManager.getLogger()

    private val data = mutableMapOf<String, MutableMap<String, String>>()

    init {
        jdbcTemplate.queryForList("SELECT * FROM code_mapping").forEach {
            val type = it["type"] as String
            val key = (it["from_code"] as String).toLowerCase()
            val value = it["to_code"] as String

            data.getOrPut(type) { mutableMapOf() }[key] = value
        }

        logger.info("code mapping loaded")
    }

    override fun getValue(type: String, key: String) = data[type]?.get(key.toLowerCase())
}

引申阅读

https://blog.wuwii.com/springboot-actuator.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值