- 添加jedis依赖
在项目pom.xml文件中添加依赖
<!-- 添加jedis依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
- 添加redis配置
在项目resources目录中找到application.properties文件添加reids配置信息
# redis
redis.host=10.x.x.x
redis.port=6379 //redis端口
redis.timeout=3
redis.password=xxxx
redis.poolMaxTotal=10 //最大连接池
redis.poolMaxIdle=10 //最大休闲连接
redis.poolMaxWait=3
- 测试例子
首先我们需要定义一个RedisConfig配置类,通过这个配置类对redis的相关属性进行设置与获取
@Component
@ConfigurationProperties(prefix="redis")
public class RedisConfig {
private String host;
private int port;
private String password;
private int timeout;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getPoolMaxTotal() {
return poolMaxTotal;
}
public void setPoolMaxTotal(int poolMaxTotal) {
this.poolMaxTotal = poolMaxTotal;
}
public int getPoolMaxIdle() {
return poolMaxIdle;
}
public void setPoolMaxIdle(int poolMaxIdle) {
this.poolMaxIdle = poolMaxIdle;
}
public int getPoolMaxWait() {
return poolMaxWait;
}
public void setPoolMaxWait(int poolMaxWait) {
this.poolMaxWait = poolMaxWait;
}
}
接下来,我们就要测试连接redis是否成功.在SpringBoot->Controller
层中写上一个获取某个key的值功能
通常控制层一般调用服务层方法,也就是我们要在服务层里获取Jedis类的实例对象,最后我们实例对象调用相关的方法jedis.get(key)
来获取键的值,
控制层代码如下
@Controller
public class DemoController {
@Autowired
RedisService redisService;
@RequestMapping("/db/getredis")
@ResponseBody
public Result<String> getRedis()
{
String strVal = redisService.getInstance().get("k1");
return Result.success(strVal);
}
}
服务层代码如下
@Service
public class RedisService {
@Autowired
JedisPool jedisPool;
public Jedis getInstance(){
Jedis jedis = jedisPool.getResource();
return jedis;
}
}