使用Lettuce作為客戶端
- 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
- 配置文件
spring:
redis:
timeout: 60s
host:
port: 6379
password:
lettuce:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
- 使用
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String get(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
}
做了以上三步就可以順利操作redis了。
使用jedis作為客戶端
springboot2.0中默認(rèn)是使用 Lettuce來集成Redis服務(wù),spring-boot-starter-data-redis默認(rèn)只引入了 Lettuce包,并沒有引入 jedis包支持。所以在我們需要手動(dòng)引入 jedis的包,并排除掉 lettuce的包。
- 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
- 配置文件
spring:
redis:
timeout: 60s
host:
port: 6379
password:
# lettuce:
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
- 配置ConnectionFactory
在 springoot 2.x版本中,默認(rèn)采用的是 Lettuce實(shí)現(xiàn)的,所以無法初始化出 Jedis的連接對(duì)象 JedisConnectionFactory,所以我們需要手動(dòng)配置并注入。springboot2.x通過以上方式集成Redis并不會(huì)讀取配置文件中的 spring.redis.host等這樣的配置,需要手動(dòng)配置:
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setHostName(host);
config.setPort(port);
config.setPassword(RedisPassword.of(password));
return new JedisConnectionFactory(config);
}
以上就可以使用了。
使用redission作為客戶端
- 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.12.3</version>
</dependency>
- 配置文件
spring:
redis:
timeout: 60s
host:
port: 6379
password:
- 使用
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String get(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
}