Jedis基于springboot的配置

配置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();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值