springboot2.1.2整合jedis
时间: 2023-09-15 19:17:56 浏览: 80
springboot 整合redis
首先,需要在pom.xml文件中添加jedis依赖:
```xml
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>
```
然后,创建一个JedisConfig类,配置JedisPool连接池和JedisConnectionFactory连接工厂:
```java
@Configuration
public class JedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis;
@Bean
public JedisPool jedisPool() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
return new JedisPool(jedisPoolConfig, host, port, timeout, password);
}
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName(host);
jedisConnectionFactory.setPort(port);
jedisConnectionFactory.setPassword(password);
jedisConnectionFactory.setTimeout(timeout);
return jedisConnectionFactory;
}
}
```
最后,在需要使用redis的类中注入JedisPool或JedisConnectionFactory即可:
```java
@Service
public class RedisService {
@Autowired
private JedisPool jedisPool;
public void set(String key, String value) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.set(key, value);
}
}
public String get(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.get(key);
}
}
}
```
以上就是springboot2.1.2整合jedis的简单步骤。
阅读全文