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
}
}