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<String, Object> deviceRedisTemplate() {
final RedisTemplate<String, Object> template = new RedisTemplate<>();
JedisConnectionFactory jedisConnectionFactory = jedisConnectionFactory();
jedisConnectionFactory.setDatabase(deviceDatabaseId); //設(shè)置db
template.setConnectionFactory(jedisConnectionFactory);
logger.info("host:{}, port:{}, database:{}", jedisConnectionFactory.getHostName(),jedisConnectionFactory.getPort(), jedisConnectionFactory.getDatabase());
//設(shè)置序列化Key的實(shí)例化對(duì)象
template.setKeySerializer(new StringRedisSerializer());
//設(shè)置序列化Value的實(shí)例化對(duì)象
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") //指定使用那一個(gè)RedisTemplate 對(duì)應(yīng)配置類中的 @Bean(name = "device")
protected RedisTemplate<String, Object> redisTemplate;
public void hset(String key,String field,Object value){
redisTemplate.opsForHash().put(key,field,value);
}
public void hset(String key,Map<String,Object> map){
redisTemplate.opsForHash().putAll(key,map);
}
/**
* 獲取map緩存
* @param key
* @return
*/
public Map<Object, Object> hgetAll(String key){
Map<Object, Object> 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;