Springboot整个Guava本地缓存,处理本地缓存一致性问题

添加依赖

    <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>

封装通用工具类

@Component
public class CacheComponent {
    private static final Cache<String, Object> CACHE = CacheBuilder.newBuilder()
            .initialCapacity(64)
            .maximumSize(100)
            .concurrencyLevel(5)
            .expireAfterWrite(2, TimeUnit.HOURS)
            .build();

    public <T> T get(String key, Supplier<T> supplier) {
        Object value = CACHE.getIfPresent(key);
        if (value != null) {
            return (T) value;
        }
        // 缓存中没有,调用回调
        T result = supplier.get();
        if (result != null) {
            CACHE.put(key, result);
        }
        return result;
    }
}

 调用示例

       Map<String, String> map = cacheComponent.get(CacheKeyConstants.ALL_CATEGORY, () -> {
            return xxxComponent.allCategroy();
        });

 本地缓存一致性解决方法

通过redis 发布订阅

订阅配置

@Autowired
    private MessageListener listener;

@Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        // 监听频道 "guava:cache:invalidate"
        container.addMessageListener(listener, new ChannelTopic("test"));
        container.addMessageListener(listener, new ChannelTopic("test2"));
        return container;
    }

    @Bean
    public MessageListener messageListener() {
        return new MessageListener() {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
                String key = new String(message.getBody(), StandardCharsets.UTF_8);
                System.out.println("[收到Redis广播] 清除本地缓存 key = " + key);
                System.out.println("[收到Redis广播] 清除本地缓存 channel = " + channel);
         //让本地缓存过期
         xxxx.invalidate(key);
} }; }

发布

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("test")
    public void test(String param){
        System.out.println("请求参数:"+param);
        redisTemplate.convertAndSend("test",param);
        redisTemplate.convertAndSend("test2",param);
    }
posted @ 2025-06-05 19:14  陈彦斌  阅读(24)  评论(0)    收藏  举报