概述
importcom.fasterxml.jackson.annotation.JsonAutoDetect;importcom.fasterxml.jackson.annotation.PropertyAccessor;importcom.fasterxml.jackson.databind.ObjectMapper;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.data.redis.connection.RedisConnectionFactory;importorg.springframework.data.redis.connection.RedisPassword;importorg.springframework.data.redis.connection.RedisStandaloneConfiguration;importorg.springframework.data.redis.connection.jedis.JedisClientConfiguration;importorg.springframework.data.redis.connection.jedis.JedisConnectionFactory;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.core.ValueOperations;importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;importorg.springframework.data.redis.serializer.RedisSerializer;importorg.springframework.data.redis.serializer.StringRedisSerializer;importorg.springframework.stereotype.Component;importredis.clients.jedis.JedisPoolConfig;importjavax.annotation.PostConstruct;importjava.io.Serializable;importjava.util.HashMap;importjava.util.Map;importjava.util.concurrent.TimeUnit;
@Component
@Slf4jpublic classRedisConfig {
@Value("${redis.host}")privateString hostName;
@Value("${redis.port}")private intport;
@Value("${redis.password}")privateString passWord;
@Value("${redis.maxIdle}")private intmaxIdl;
@Value("${redis.minIdle}")private intminIdl;
@Value("${redis.timeout}")private inttimeout;
@Value("${sessionCodeDb}")private intsessionCodeDb;
@Value("${bicycleInfoDb}")private intbicycleInfoDb;
@Value("${currentLocationDb}")private intcurrentLocationDb;
@Value("${lockDb}")private intlockDb;
@Value("${ebikeNoDb}")private intebikeNoDb;
@Value("${bikeNoDb}")private intbikeNoDb;public static Map> redisTemplateMap = new HashMap<>();
@PostConstructpublic void initRedisTemp() throwsException{
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 redisTemplateObject(Integer dbIndex) throwsException {
RedisTemplate redisTemplateObject = new RedisTemplate();
redisTemplateObject.setConnectionFactory(redisConnectionFactory(jedisPoolConfig(),dbIndex));
setSerializer(redisTemplateObject);
redisTemplateObject.afterPropertiesSet();returnredisTemplateObject;
}/*** 连接池配置信息
*@return
*/
publicJedisPoolConfig jedisPoolConfig() {
JedisPoolConfig poolConfig=newJedisPoolConfig();//最大连接数
poolConfig.setMaxIdle(maxIdl);//最小空闲连接数
poolConfig.setMinIdle(minIdl);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setNumTestsPerEvictionRun(10);
poolConfig.setTimeBetweenEvictionRunsMillis(60000);//当池内没有可用的连接时,最大等待时间
poolConfig.setMaxWaitMillis(10000);//------其他属性根据需要自行添加-------------
returnpoolConfig;
}/*** jedis连接工厂
*@paramjedisPoolConfig
*@return
*/
public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig,intdb) {//单机版jedis
RedisStandaloneConfiguration redisStandaloneConfiguration =
newRedisStandaloneConfiguration();//设置redis服务器的host或者ip地址
redisStandaloneConfiguration.setHostName(hostName);//设置默认使用的数据库
redisStandaloneConfiguration.setDatabase(db);//设置密码
redisStandaloneConfiguration.setPassword(RedisPassword.of(passWord));//设置redis的服务的端口号
redisStandaloneConfiguration.setPort(port);//获得默认的连接池构造器(怎么设计的,为什么不抽象出单独类,供用户使用呢)
JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcb =(JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)JedisClientConfiguration.builder();//指定jedisPoolConifig来修改默认的连接池构造器(真麻烦,滥用设计模式!)
jpcb.poolConfig(jedisPoolConfig);//通过构造器来构造jedis客户端配置
JedisClientConfiguration jedisClientConfiguration =jpcb.build();//单机配置 + 客户端配置 = jedis连接工厂
return newJedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
}private void setSerializer(RedisTemplatetemplate) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(
Object.class);
ObjectMapper om= newObjectMapper();
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);//在使用String的数据结构的时候使用这个来更改序列化方式
RedisSerializer stringSerializer = newStringRedisSerializer();
template.setKeySerializer(stringSerializer );
template.setValueSerializer(stringSerializer );
template.setHashKeySerializer(stringSerializer );
template.setHashValueSerializer(stringSerializer );
}/*** 删除对应的value
*@paramkey*/
public void remove(final String key,intdb) {
RedisTemplate redisTemplate =getRedisTemplateByDb(db);if(exists(key,redisTemplate)) {
redisTemplate.delete(key);
}
}/*** 判断缓存中是否有对应的value
*@paramkey
*@return
*/
public boolean exists(final String key,RedisTemplateredisTemplate) {returnredisTemplate.hasKey(key);
}/*** 读取缓存
*@paramkey
*@return
*/
public Object get(final String key,intdb) {
RedisTemplate redisTemplate =getRedisTemplateByDb(db);
Object result= null;
ValueOperations operations =redisTemplate.opsForValue();
result=operations.get(key);returnresult;
}/*** 写入缓存
*@paramkey
*@paramvalue
*@return
*/
public boolean set(final String key, Object value,intdb) {
RedisTemplate redisTemplate =getRedisTemplateByDb(db);boolean result = false;try{
ValueOperations operations =redisTemplate.opsForValue();
operations.set(key, value);
result= true;
}catch(Exception e) {
log.error("set cache error", e);
}returnresult;
}/*** 根据key 获取过期时间
*@paramkey 键 不能为null
*@return返回0代表为永久有效*/
public long getExpire(String key,TimeUnit unit,intdb) {
RedisTemplate redisTemplate =getRedisTemplateByDb(db);returnredisTemplate.getExpire(key, unit);
}/*** 根据db 获取对应的redisTemplate实例
*@paramdb
*@return
*/
public RedisTemplate getRedisTemplateByDb(intdb){returnredisTemplateMap.get(db);
}
}
最后
以上就是生动乌冬面为你收集整理的java连接redis不同的db_Redis 配置连接池,redisTemplate 操作多个db数据库,切换多个db,解决JedisConnectionFactory的设置连接方法过时问题。(转)...的全部内容,希望文章能够帮你解决java连接redis不同的db_Redis 配置连接池,redisTemplate 操作多个db数据库,切换多个db,解决JedisConnectionFactory的设置连接方法过时问题。(转)...所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复