环境
- springmvc
- jdk1.8
- maven
redis.properties配置文件
#redis setting
redis.host=localhost
redis.port=6379
redis.password=
redis.maxIdle=200
redis.minIdle=0
redis.maxActive=50
redis.maxWait=10000
redis.testOnBorrow=true
redis.timeout=100000
#定义需要使用的db
//#sessionCode DB
sessionCodeDb = 0
//#车辆基本信息 DB
bicycleInfoDb = 15
//#当前位置信息 DB
currentLocationDb = 14
//#锁车/解锁 DB
lockDb = 13
//#根据车牌获取电子车牌 DB
ebikeNoDb = 12
//#根据电子车牌获取车牌 DB
bikeNoDb = 11
pom.xml依赖
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<spring.version>5.1.2.RELEASEspring.version>
properties>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>2.9.3version>
dependency>
<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-redisartifactId>
<version>2.0.14.RELEASEversion>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.11version>
dependency>
<dependency>
<groupId>net.sf.json-libgroupId>
<artifactId>json-libartifactId>
<version>2.4version>
<classifier>jdk15classifier>
dependency>
RedisConfig.java 配置类 初始化redis连接池
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPoolConfig;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class RedisConfig {
@Value("${redis.host}")
private String hostName;
@Value("${redis.port}")
private int port;
@Value("${redis.password}")
private String passWord;
@Value("${redis.maxIdle}")
private int maxIdl;
@Value("${redis.minIdle}")
private int minIdl;
@Value("${redis.timeout}")
private int timeout;
@Value("${sessionCodeDb}")
private int sessionCodeDb;
@Value("${bicycleInfoDb}")
private int bicycleInfoDb;
@Value("${currentLocationDb}")
private int currentLocationDb;
@Value("${lockDb}")
private int lockDb;
@Value("${ebikeNoDb}")
private int ebikeNoDb;
@Value("${bikeNoDb}")
private int bikeNoDb;
public static Map<Integer,RedisTemplate<Serializable, Object>> redisTemplateMap = new HashMap<>();
@PostConstruct
public void initRedisTemp() throws Exception{
log.info("###### START 初始化 Redis 连接池 START ######");
redisTemplateMap.put(sessionCodeDb,redisTemplateObject(sessionCodeDb));
redisTemplateMap.put(bicycleInfoDb,redisTemplateObject(bicycleInfoDb));
redisTemplateMap.put(currentLocationDb,redisTemplateObject(currentLocationDb));
redisTemplateMap.put(lockDb,redisTemplateObject(lockDb));
redisTemplateMap.put(ebikeNoDb,redisTemplateObject(ebikeNoDb));
redisTemplateMap.put(bikeNoDb,redisTemplateObject(bikeNoDb));
log.info("###### END 初始化 Redis 连接池 END ######");
}
public RedisTemplate<Serializable, Object> redisTemplateObject(Integer dbIndex) throws Exception {
RedisTemplate<Serializable, Object> redisTemplateObject = new RedisTemplate<Serializable, Object>();
redisTemplateObject.setConnectionFactory(redisConnectionFactory(jedisPoolConfig(),dbIndex));
setSerializer(redisTemplateObject);
redisTemplateObject.afterPropertiesSet();
return redisTemplateObject;
}
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig poolConfig=new JedisPoolConfig();
poolConfig.setMaxIdle(maxIdl);
poolConfig.setMinIdle(minIdl);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setNumTestsPerEvictionRun(10);
poolConfig.setTimeBetweenEvictionRunsMillis(60000);
poolConfig.setMaxWaitMillis(10000);
return poolConfig;
}
public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig,int db) {
RedisStandaloneConfiguration redisStandaloneConfiguration =
new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(hostName);
redisStandaloneConfiguration.setDatabase(db);
redisStandaloneConfiguration.setPassword(RedisPassword.of(passWord));
redisStandaloneConfiguration.setPort(port);
JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb =
(JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)JedisClientConfiguration.builder();
jpcb.poolConfig(jedisPoolConfig);
JedisClientConfiguration jedisClientConfiguration = jpcb.build();
return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
}
private void setSerializer(RedisTemplate<Serializable, Object> template) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setKeySerializer(template.getStringSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer );
template.setValueSerializer(stringSerializer );
template.setHashKeySerializer(stringSerializer );
template.setHashValueSerializer(stringSerializer );
}
public void remove(final String key,int db) {
RedisTemplate<Serializable, Object> redisTemplate = getRedisTemplateByDb(db);
if (exists(key,redisTemplate)) {
redisTemplate.delete(key);
}
}
public boolean exists(final String key,RedisTemplate<Serializable, Object> redisTemplate) {
return redisTemplate.hasKey(key);
}
public Object get(final String key,int db) {
RedisTemplate<Serializable, Object> redisTemplate = getRedisTemplateByDb(db);
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
public boolean set(final String key, Object value,int db) {
RedisTemplate<Serializable, Object> redisTemplate = getRedisTemplateByDb(db);
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
log.error("set cache error", e);
}
return result;
}
public long getExpire(String key,TimeUnit unit,int db) {
RedisTemplate<Serializable, Object> redisTemplate = getRedisTemplateByDb(db);
return redisTemplate.getExpire(key, unit);
}
public RedisTemplate<Serializable, Object> getRedisTemplateByDb(int db){
return redisTemplateMap.get(db);
}
}
在其他类中的使用
@Autowired
private RedisConfig redisUtil;
public static Integer sessionCodeDb = 0;
public String getUserIdBySessionCode(String sessionCode){
try {
Object obj = redisUtil.get(sessionCode,sessionCodeDb);
if(obj!=null) {
return obj.toString();
}else{
return null;
}
}catch (Exception e){
e.printStackTrace();
return null;
}
}