本文探究的是,在main方法中如何极简得使用RedisTemplate(归功于SpringBoot及其约定大于配置的设计思想)
旨在研究SpringBoot源码,理解其构建体系
平时我们在项目中使用Reids一般直接这样使用
引入redis依赖
<!-- Redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
代码中这样使用
@Autowired
RedisTemplate redisTemplate;
或者
@Autowired
StringRedisTemplate redisTemplate;
// Redis的原生的连接工厂,用于提供和维护Redis连接,为RedisConnectionFactory的子类
private static final LettuceConnectionFactory factory = new LettuceConnectionFactory();
// 操作Redis的工具类,其构造方法有 RedisConnectionFactory
private static final StringRedisTemplate redisTemplate = new StringRedisTemplate(factory);
static {
// Bean后置初始化操作,用于最终的配置和初始化,以供正式使用
factory.afterPropertiesSet();
}
public static void main(String[] args) {
// 为方便演示此处设值后就打印此键值以验证程序正确
final String key = "111";
setVal(key, "222");
System.out.println(getVal(key));
}
// 简单的Redis设值方法
private static void setVal(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
// 简单的Redis取值方法
private static String getVal(String key) {
return redisTemplate.opsForValue().get(key);
}
运行main方法即可得到控制台输出