Springboot整合Redis三种模式的连接方式
写在前面
本文只是简单整理,并没有过多研究,所以难免有纰漏,还请大家指出。
环境介绍
机器 10.3.50.182
Springboot 2.0.3.RELEASE
Redis redis-4.0.1
maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
redis连接
standalone模式
默认配置
配置信息
application.properties中的配置如下(具体配置根据自身情况)
spring.redis.database=3
spring.redis.host=10.3.50.182
spring.redis.port=27000
spring.redis.password=RedisPass
spring.redis.jedis.pool.max-wait=3600
spring.redis.jedis.pool.max-active=1
spring.redis.jedis.pool.max-idle=1
spring.redis.jedis.pool.min-idle=1
spring.redis.timeout=3600
代码调用
在需要使用的类中直接注入RedisTemplate即可
@Resource
private RedisTemplate<String, String> redisTemplate;
自定义配置
配置信息
application.properties中的配置如下(具体配置根据自身情况)
#### Server
spring.redis.password=RedisPass
spring.redis.host=10.3.50.182
spring.redis.port=27000
spring.redis.jedis.pool.max-wait=3600
spring.redis.jedis.pool.max-active=1
spring.redis.jedis.pool.max-idle=1
spring.redis.jedis.pool.min-idle=1
spring.redis.timeout=3600
### Redis Server db user
spring.redis.user.database=15
spring.redis.basic.database=14
spring.redis.auction.database=13
spring.redis.default.database=12
代码调用
不同的库,配置不同的RedisTemplate实例
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class DefaultRedisConfig {
@Value("${spring.redis.user.database}")
private int userDB;
@Value("${spring.redis.basic.database}")
private int basicDB;
@Value("${spring.redis.auction.database}")
private int auctionDB;
@Value("${spring.redis.default.database}")
private int defaultDB;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String pwd;
public JedisConnectionFactory defaultRedisConnectionFactory(int db){
return getJedisConnectionFactory(db, host, port, pwd);
}
private JedisConnectionFactory getJedisConnectionFactory(int dbIndex, String host, int port, String pwd) {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration