配置redisConfig类读取配置文件中的redis信息
@Configuration
@EnableCaching//标注启动缓存.
public class RedisConfiguration<T> {
@Value("${spring.redis.database}")
private int dateBase;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.pool.max-active}")
private int maxTotal;
@Value("${spring.redis.pool.max-wait}")
private int maxWait;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.timeout}")
private int timeout;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setDatabase(dateBase);
factory.setHostName(host);
factory.setPort(port);
factory.setPassword(password);
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWaitMillis(maxWait);
poolConfig.setMaxTotal(maxTotal);
factory.setPoolConfig(poolConfig);
factory.setTimeout(timeout);
return factory;
}
// public Jedis getJedis() {
// Jedis jedis = new Jedis(host,port);
// return jedis;
// }
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* RedisTemplate配置
*
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, T> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, T> template = new RedisTemplate<String, T>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
// template.setValueSerializer(new JdkSerializationRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
}
在RedisService中建立Jedis链接,方便调用(注:这里选择的是redis中的索引为6的库,默认为0):
public Jedis getJedis() {
Jedis jedis = new Jedis(redisConfiguration.getHost(),redisConfiguration.getPort());
jedis.auth(redisConfiguration.getPassword());
jedis.select(6);
return jedis;
}
使用后需要释放jedis,下面是使用的时候的一个简单的小demo,获取,存储,设置过期时间,关闭。
Jedis jedis = redisService.getJedis();
Map<String,String> limitMap = new HashMap<>();
limitMap = jedis.hgetAll("bankLimitAmount");
jedis.hmset("bankLimitAmount", limitMap);
jedis.expire("bankLimitAmount", 86400);
jedis.close();