Spring配置Redis
1. 加入Spring Data Redis的Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 注入RedisTemplate的Bean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 设置连接工厂类
template.setConnectionFactory(factory);
// 设置key的序列化器
template.setKeySerializer(RedisSerializer.string());
// 设置value的序列化器
template.setValueSerializer(RedisSerializer.json());
// 设置hash key的序列化器
template.setHashKeySerializer(RedisSerializer.string());
// 设置hash value的序列化器
template.setHashValueSerializer(RedisSerializer.json());
// 设置完成
template.afterPropertiesSet();
return template;
}
}
3. 添加配置信息
#redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=0
4. 使用RedisTemplate
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = AccumulatorApplication.class)
public class RedisTests {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
public void testRedisValue() {
// 测试Redis的Value
String redisKey = "test:value";
redisTemplate.opsForValue().set(redisKey, "hello");
Object result = redisTemplate.opsForValue().get(redisKey);
System.out.println(result);
}
@Test
public void testRedisTransaction() {
// 测试Redis事务
List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
@Override
public List<Object> execute(RedisOperations operations) throws DataAccessException {
operations.multi();
operations.opsForValue().set("test:01", 1);
operations.opsForValue().set("test:02", 2);
operations.opsForValue().set("test:03", 3);
System.out.println(operations.opsForValue().get("test:01")); //读取不到结果
return operations.exec();
}
});
System.out.println(txResults);
}
}
5. 补充说明
- 因为注入RedisTemplate的时候设置的value和hash value的序列化器为json,所以使用RedisTemplate时,value和hash value可以是任意的POJO。
- Redis集群环境不支持事务,在部署生产环境时,要确认生产环境是否为Redis集群。