spring boot 项目启动自动清除redis中的key值

本文介绍了一种在Spring Boot应用中使用Redis作为缓存时,如何实现实时更新缓存的方法。通过创建实现CommandLineRunner接口的类,定义缓存key前缀,并利用RedisTemplate和RedisKeyCommands接口的del方法,可以有效地删除指定前缀的key,从而在数据库更新时同步刷新Redis缓存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中使用了redis缓存,但在修改了数据库时,redis中的数据无法实时更新,这就需要删除掉redis库中的key,重新加载缓存。

具体实现如下:

1、新建实现类并继承CommandLineRunner接口;

2、定义redis的key值前缀;

3、用redisTemplate获取redis连接;

4、调用RedisKeyCommands接口中的del方法,根据key值前缀删除redis库中对应的key;

下面是代码实现:

a、删除单个key值代码:

package com.platinum.redis.runner;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class CacheUpdateRunner implements CommandLineRunner {
   
	@SuppressWarnings("rawtypes")
	@Autowired
	private RedisTemplate redisTemplate;
	
	private static final String CACHE_KEY_PREFIX = "age" ;
	@Override
	public void run(String... args) throws Exception {	
		  String pattern = CACHE_KEY_PREFIX + "*" ;
	        RedisConnection connection = redisTemplate
	                .getConnectionFactory().getConnection();

	        Set<byte[]> caches = connection.keys(pattern.getBytes());
	        if(!caches.isEmpty()){
	            connection.del(caches.toArray(new byte[][]{}));
	        }

	}

b、删除多个指定key的代码:

package com.dbs.backtesting.runner;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class CacheUpdateRunner implements CommandLineRunner {
   
	@SuppressWarnings("rawtypes")
	@Autowired
	private RedisTemplate redisTemplate;
	
	private static final String CACHE_KEY_PREFIX_ECO = "economicindicator*" ;
	private static final String CACHE_KEY_PREFIX_GET_ECO = "getEco*" ;
	
	@Override
	public void run(String... args) throws Exception {	
		List<String> list = new ArrayList<String>();
		list.add(CACHE_KEY_PREFIX_ECO);
		list.add(CACHE_KEY_PREFIX_GET_ECO);
	    RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
	    for(String patterns : list) {
	    	  Set<byte[]> caches = connection.keys(patterns.getBytes());
		        if(!caches.isEmpty()){
		            connection.del(caches.toArray(new byte[][]{}));
		        }
	    	}
	}

}

注意:需要在类中添加@Component注解。

Spring Boot项目中添加Azure Redis Cache依赖,可以通过以下几个步骤实现: 1. **添加Maven依赖**: 在你的`pom.xml`文件中添加以下依赖,用于集成Spring Data Redis和Azure Redis Cache。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>com.microsoft.azure</groupId> <artifactId>azure-spring-boot-starter</artifactId> <version>2.3.0</version> </dependency> ``` 2. **配置application.properties或application.yml**: 在你的Spring Boot项目的配置文件中添加Redis缓存的配置信息。例如,使用`application.properties`文件进行配置: ```properties spring.redis.host=<your-azure-redis-cache-name>.redis.cache.windows.net spring.redis.port=6380 spring.redis.password=<your-access-key> ``` 或者使用`application.yml`文件进行配置: ```yaml spring: redis: host: <your-azure-redis-cache-name>.redis.cache.windows.net port: 6380 password: <your-access-key> ``` 3. **创建Redis配置类**: 如果你需要自定义Redis配置,可以创建一个配置类。例如: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { @Bean public LettuceConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); return template; } } ``` 4. **使用RedisTemplate进行操作**: 在你的服务或控制器中注入`RedisTemplate`并使用它进行数据操作。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class MyService { @Autowired private RedisTemplate<String, Object> redisTemplate; public void saveData(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object getData(String key) { return redisTemplate.opsForValue().get(key); } } ``` 通过以上步骤,你就可以在Spring Boot项目中成功添加并使用Azure Redis Cache了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值