1.添加依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.修改配置文件
将application.properties改为yml并添加如下配置:
spring:
redis:
database: 0
host: 192.168.145.128
password: 123456
port: 6379
jedis: #连接池相关配置
pool:
max-active: 8 #最大连接数
max-idle: 8 #最大空闲数
min-idle: 1 #最小空闲数
创建jedisConfig类:
package com.example.moduledemo01.config;
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
public class jedisConfig {
private int database;
private String host;
private String password;
private int port;
/*
* 1.jedis连接池配置(得到JDBC连接池)
*
* */
@Bean
public JedisPool jedisPool(){
/*
* 连接池
* */
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(8);
jedisPoolConfig.setMaxIdle(8);
jedisPoolConfig.setMinIdle(1);
JedisPool jedisPool=new JedisPool(jedisPoolConfig,host,port,2000,password);
return jedisPool;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
测试:
package com.example.moduledemo01;
@SpringBootTest
class Moduledemo01ApplicationTests {
@Autowired
private JedisPool jedisPool;
@Test
void contextLoads() {
//从连接池中得到链接对象
Jedis jedis = jedisPool.getResource();
jedis.set("java111","springboot");
System.out.println(jedis.get("java111"));
jedis.close();
}
}