SpringBoot 整合 Redis
1 引入redis
通过springboot初始化整合redis
其生成的pom.xml中会有
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
通过添加maven依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2 配置连接信息
如果要远程连接服务器上的redis需要将redis.conf中的bind:127.0.0.1注释掉,并且将protected-mode yes修改为protected-mode no
# redis所在主机的ip
spring.redis.host=127.0.0.1
# redis所在主机配置的端口
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.lettuce.shutdown-timeout=0
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 500
min-idle: 0
lettuce:
shutdown-timeout: 0
3 测试连接
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringredisApplicationTests {
@Autowired
private RedisTemplate<String,String> redisTemplate;
/**
* spring 初始化方法连接redis
*/
@Test
public void setRedisString() {
redisTemplate.opsForValue().set("connection_test", "ok");
System.out.println(redisTemplate.opsForValue().get("connection_test"));
}
/**
* 手动导入maven依赖
*/
@Test
public void setRedisStringV2() {
GenericObjectPoolConfig pool = new GenericObjectPoolConfig();
JedisPool jedisPool = new JedisPool(pool, "127.0.0.1", 6379);
Jedis jedis = null;
try {
// 从连接池获取jedis对象
jedis = jedisPool.getResource();
// 执行操作
jedis.set("hello", "world");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
// 如果使用连接池的话 close操作代表归还连接池而不是关闭连接。
jedis.close();
}
}
}
}