1、添加依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、资源文件配置
spring.redis.host=localhost
spring.redis.port=6379
3、配置加载redis
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer(Object.class);
// 设置键(key)的序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
// 设置value序列化
redisTemplate.setValueSerializer(serializer);
// 设置HashKey序列化 为啥要hashkey
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// 设置HashValue序列化
redisTemplate.setHashValueSerializer(serializer);
// 默认序列化
redisTemplate.setDefaultSerializer(new StringRedisSerializer());
return redisTemplate;
}
}
4、在service里注入redisTemplat并使用
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public User login(String userName, String password) {
redisTemplate.opsForValue().set(userName, "success");
Object o=redisTemplate.opsForValue().get(userName);
System.out.println(o);
return mapper.login(userName,password);
}