【应用】SpringBoot 整合 Redis

本文介绍了如何在SpringBoot项目中整合Redis,并展示了通过Lettuce和Jedis两种客户端进行连接的配置与测试。首先,添加相关依赖,然后配置Redis的主机和端口。在测试中,使用RedisTemplate进行数据操作。接着,通过更改配置文件,将默认的Lettuce连接池切换到Jedis。最后,验证了使用Jedis连接时的客户端类型。
摘要由CSDN通过智能技术生成

SpringBoot 的整合 Redis

引入依赖:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置redis地址以及端口号:

spring:
  redis:
    host: 192.168.0.107
    port: 6379

测试:

package com.zqf.springboot_redis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class SpringbootRedisApplicationTests {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Test
    void testRedis() {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set("hello", "world");
        System.out.println(operations.get("hello")); // world
        System.out.println(redisConnectionFactory.getClass()); // class org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory
    }

}

springboot2.4.2 默认使用 Lettuce 连接池,要想切换到 jedis,首先引入依赖

<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
</dependency>

修改配置文件,指定客户端连接类型为 jedis

spring:
  redis:
    host: 192.168.0.107
    port: 6379
    client-type: jedis

测试:

package com.zqf.springboot_redis;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class SpringbootRedisApplicationTests {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Test
    void testRedis() {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set("hello", "world!!!");
        System.out.println(operations.get("hello")); // world!!!
        System.out.println(redisConnectionFactory.getClass()); // class org.springframework.data.redis.connection.jedis.JedisConnectionFactory
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值