SpringBoot 基于RedisTemplate 探索默认配置

本文探究的是,在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方法即可得到控制台输出

代码输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值