第一步:配置redis
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.keyvalue.core.mapping.KeyPrefix;
import org.springframework.data.keyvalue.core.query.KeyValueQuery;
import java.time.Duration;
@Configuration
public class RedisConfig {
public static final String redisPrefix="xxxx:";
@Bean
public RedisTemplate<String, String> redisTemplate(StringRedisTemplate stringRedisTemplate) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setKeySerializer(stringRedisTemplate.getKeySerializer());
template.setValueSerializer(stringRedisTemplate.getValueSerializer());
template.setHashKeySerializer(stringRedisTemplate.getHashKeySerializer());
template.setHashValueSerializer(stringRedisTemplate.getHashValueSerializer());
template.setEnableTransactionSupport(true);
template.setConnectionFactory(stringRedisTemplate.getConnectionFactory());
// 设置key的前缀
KeyPrefix keyPrefix = new KeyPrefix() {
@Override
public byte[] prefix(String key) {
return (redisPrefix + ":" + key).getBytes();
}
};
template.setKeyGenerator(keyPrefix);
return template;
}
}
第二步:在使用
java
//在代码中注入RedisTemplate
@Autowired
private RedisTemplate<String, String> redisTemplate;
//写个方法调用
public void setValue(String key, String value) {
// //使用,添加一个缓存,添加后使用redis管理工具查看,此时会发现key将会自动加上前缀"redisPrefix:"
redisTemplate.opsForValue().set(key, value, Duration.ofMinutes(300));
}