Spring boot redis切换db

1.redis 配置类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
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 DeviceRedisConfig {

private static final Logger logger = LoggerFactory.getLogger(DeviceRedisConfig.class);


@Autowired
private RedisTemplate redisTemplate;

@Value("15")
private int deviceDatabaseId;


@Scope(value = "prototype")
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = (JedisConnectionFactory) redisTemplate.getConnectionFactory();
factory.setUsePool(true);
return factory;
}

   
@Bean(name = "device")
public RedisTemplate deviceRedisTemplate() {
    final RedisTemplate template = new RedisTemplate<>();
    JedisConnectionFactory jedisConnectionFactory = jedisConnectionFactory();
    jedisConnectionFactory.setDatabase(deviceDatabaseId);  //设置db
    template.setConnectionFactory(jedisConnectionFactory);
    logger.info("host:{}, port:{}, database:{}", jedisConnectionFactory.getHostName(),jedisConnectionFactory.getPort(), jedisConnectionFactory.getDatabase());
    
    //设置序列化Key的实例化对象
    template.setKeySerializer(new StringRedisSerializer());
    //设置序列化Value的实例化对象
    template.setValueSerializer(new StringRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new StringRedisSerializer());
    return template;
}

}

2. reids工具类

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class DeviceRedisUtils {

@Autowired
@Qualifier("device")   //指定使用那一个RedisTemplate 对应配置类中的 @Bean(name = "device")
protected  RedisTemplate redisTemplate;


public void  hset(String key,String field,Object value){
    redisTemplate.opsForHash().put(key,field,value);
}

public void hset(String key,Map map){
    redisTemplate.opsForHash().putAll(key,map);
}

/**
 * 获取map缓存
 * @param key
 * @return
 */
public Map hgetAll(String key){
    Map map =   redisTemplate.opsForHash().entries(key);
    return map;
}

public Object hget(String key,String filed){
    return redisTemplate.opsForHash().get(key,filed);
}

}

3. 具体使用

   @Autowired
private DeviceRedisUtils deviceRedisUtils;

你可能感兴趣的:(Spring boot redis切换db)