| | |
| | | package com.hx.redis; |
| | | |
| | | import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; |
| | | import org.springframework.data.redis.core.RedisTemplate; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | |
| | | @Resource |
| | | private RedisTemplate<String, Object> redisTemplate; |
| | | |
| | | /** |
| | | * 切换数据库 |
| | | * @param dataNumber 数据库编号 |
| | | */ |
| | | public void setDataBase(int dataNumber) { |
| | | LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory(); |
| | | if (connectionFactory != null && dataNumber != connectionFactory.getDatabase()) { |
| | | connectionFactory.setDatabase(dataNumber); |
| | | this.redisTemplate.setConnectionFactory(connectionFactory); |
| | | connectionFactory.resetConnection(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * [判断key是否存在] |
| | |
| | | |
| | | } |
| | | |
| | | } |
| | | |
| | | /** |
| | | * 设置到期时间 |
| | | * @param key 对应键 |
| | | * @param time 时长 |
| | | * @param timeUnit 时间单位 |
| | | * @return |
| | | */ |
| | | public boolean expire(String key, long time, TimeUnit timeUnit) { |
| | | try { |
| | | if (time > 0) { |
| | | return redisTemplate.expire(key, time, timeUnit); |
| | | } |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return false; |
| | | |
| | | } |
| | | return false; |
| | | } |
| | | |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @param timeOut 时间 |
| | | * @param unit 时间单位 |
| | | */ |
| | | public Boolean setIfAbsent(String key, Object value, long timeOut, TimeUnit unit) { |
| | | try { |
| | | return redisTemplate.opsForValue().setIfAbsent(key, value, timeOut, unit); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | } |