一前言:
在本章开始之前,确保自己的Redis是可以成功启动的,本篇使用的是Windows版本的Redis。
二SpringBoot中配置Redis
- 1配置POM依赖
- 2配置配置信息
- 3封装常用操作
- 4进行测试
1配置POM依赖:
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2配置配置信息
#redis服务器地址
spring.redis.host=127.0.0.1
#redis服务器连接端口
spring.redis.port=6379
#redis服务器连接密码(默认为空)
spring.redis.password=
#redis数据库索引(默认为0(0-15)
spring.redis.database=0
#redis连接池最大连接数(使用负数则代表没有连接数没有限制)
spring.redis.jedis.pool.max-active=11
#redis连接池最大阻塞等待时间
spring.redis.jedis.pool.max-wait=-1
#redis连接池最大空闲连接
spring.redis.jedis.pool.max-idle=11
#redis连接池最小空闲连接
spring.redis.jedis.pool.min-idle=0
#连接超时时间(以毫秒为单位)
spring.redis.timeout=0
3封装常用操作
package com.example.xxx.DBTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/*
封装Redis的常用操作
*/
@Component
public class RedisTools {
@Autowired
private RedisTemplate redisTemplate;
/*
数据插入
*/
public boolean set(String key,String value){
boolean result;
try{
redisTemplate.opsForValue().set(key,value);
result=true;
}
catch (Exception e){
result=false;
e.printStackTrace();
}
return result;
}
/*
获取数据
*/
public String get(String key){
String result;
try{
result=redisTemplate.opsForValue().get(key).toString();
}catch (Exception e){
result="获取失败";
e.printStackTrace();
}
return result;
}
/*
删除数据
*/
public boolean delete(String key){
boolean result;
try{
redisTemplate.delete(key);
result=true;
}catch (Exception e){
result=false;
e.printStackTrace();
}
return result;
}
}
4进行测试
package com.example.xxx.RedisTools;
import com.example.xxx.DBTools.RedisTools;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
RedisTools redisTools;
/*
测试插入方法
*/
@Test
public void TestSet(){
redisTools.set("k2","k2");
}
}
执行之前:
当前Redis数据库中是没有任何数据的:
执行之后:
多了K1这条记录
注意点:在进行测试的时候,测试类的路径必须要与该封装工具类的包名一致,否则就会出现报错:
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test
连接超时时间设置过短会导致:
java.lang.IllegalStateException: Failed to load ApplicationContext