- 导入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
- 编写application.properties配置文件,规定host和port
spring.redis.host=192.168.44.142
spring.redis.port=6379
- 编写SpringBoot主启动类
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class,args);
}
}
- 编写测试类
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedis {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testRedis(){
redisTemplate.opsForValue().set("name","yorick");
System.out.println(redisTemplate.opsForValue().get("name"));
}
}
- redisTemplate相关说明
1.对于基本类型String、list、set等操作都被放在各自的方法中,例如:opsForValue(),opsForList(),opsForSet()
2.常用操作,例如:multi,discard 等 可以直接调用。例如:redisTemplate.multi(),redisTemplate.discard(),redisTemplate.exec()
3.对连接的操作或者刷新数据库可以通过获取连接对象操作。例如:
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.flushDb();
connection.flushAll();
- 编写自定义的redisTemplate
说明:使用默认的java序列化后,在redis中存储如下信息,不直观。为解决该问题,使用自定义的redisTemplate。
127.0.0.1:6379> keys *
1) "\xac\xed\x00\x05t\x00\x04name"
@Configuration
public class RedisConfig {
@Bean
@SuppressWarnings("all")
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
//序列化配置
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
}
127.0.0.1:6379> keys *
1) "name"
网友评论