使用前需要开启Redis服务。
操作步骤:
一. 导入Spring Data Redis的maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二. 配置Redis数据源
sky:
redis:
host: localhost
port: 6379
password: ****
database: 0
三. 编写配置类,创建RedisTemplate对象
@Configuration
@Slf4j
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
log.info("开始创建RedisTemplate对象...");
RedisTemplate redisTemplate = new RedisTemplate();
// 设置redis连接工厂对象
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置redis key的序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
}
四. 通过RedisTemplate操作Redis
这里以字符串和hash为例:
@Autowired
private RedisTemplate redisTemplate;
/**
* 操作字符串
*/
@Test
public void testString(){
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("name","张三");
String name = (String) valueOperations.get("name");
System.out.println(name);
valueOperations.set("code","123456",3, TimeUnit.MINUTES);
valueOperations.setIfAbsent("code","123456");
}
/**
* 操作hash
*/
@Test
public void testHash(){
//hset hget hdel hkeys hsize hvalues
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.put("100","name","szj");
hashOperations.put("100","age",20);
String name = (String) hashOperations.get("100", "name");
System.out.println(name);
Set keys = hashOperations.keys("100");
System.out.println(keys);
List values = hashOperations.values("100");
System.out.println(values);
hashOperations.delete("100","age");
}