SpringBoot整合Redis

SpringBoot整合Redis

SpringBoot操作数据:spring-data jpa jdbc mongodb redis !
SpringData也是和SpringBoot齐名的项目!

说明︰在SpringBoot2.x之后,原来使用的jedis被替换为了lettuce

jedis :采用的直连,多个线程操作的话,是不安全的,
如果想要避免不安全的,使用jedis pool连接池!更像BIO模式

lettuce :采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!
可以减少线程数据了,更像NIO模式
请添加图片描述
请添加图片描述
请添加图片描述

@Bean
@ConditionalOnMissingBean(name = "redisTemplate")//我们可以自己自定义一个redis来代替这个默认的
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
	//默认的RedisTemplate没有过多的设置,redis对象都是需要序列化!
	//两个泛型都是Object类型,我们后续使用需要强制转换<String,Object>
   RedisTemplate<Object, Object> template = new RedisTemplate<>();
   template.setConnectionFactory(redisConnectionFactory);
   return template;
}

由于String类型是redis常用的类型,所以单独提出来了一个bean

@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
   return new StringRedisTemplate(redisConnectionFactory);
}

在这里插入图片描述

在这里插入图片描述

整合测试

  1. 导入依赖

  2. 配置连接

  3. #配置redis

spring.redis.host=192.168.1.1
spring.redis.post=6379
spring.redis.password=123456

4. 测试

@Autowired
private RedisTemplate redisTemplate;

@Test
void contextLoads() {

    //redisTemplate 操作不同的数据类型,api和我们的指令一样
    //opsForValue 操作字符串,类似String
    //opsForList  操作List,类似list
    //opsForSet
    //opsForHash
    //opsForZSet
    //opsForGeo
    //opsForHyperLogLog

    //除了进本操作,我们常用的方法都可以直接通过redisTemplate操作,
    // 比如事务,和基本的CRUD

    //获取redis的连接对象
    //RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
    //connection.flushDb();
    //connection.flushAll();


    redisTemplate.opsForValue().set("key1","hello");
    redisTemplate.opsForValue().set("key2","九头");
    System.out.println(""+redisTemplate.opsForValue().get("key1"));
    System.out.println(""+redisTemplate.opsForValue().get("key2"));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值