SpringBoot整合Redis

1.在build.gradle文件中添加依賴包

compile 'org.springframework.boot:spring-boot-starter-data-redis'

2.在appliacation.properties文件中添加配置文件

spring.redis.pool.max-idle=8
spring.redis.timeout=1000
spring.redis.pool.max-wait=-1
spring.redis.host=10.116.50.203
spring.redis.pool.min-idle=0
spring.redis.password=
spring.redis.port=31784
spring.redis.database=0
spring.redis.pool.max-active=8
saic.common.auth.redis.keypattern=UAS\:AUTHORIZATION\:%s

3.RedisTemplate配置

@Configuration
@EnableCaching
public class RedisConfig {
    /**
     * 管理緩存
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        return rcm;
    }
    /**
     * RedisTemplate配置
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

 

4.封裝RedisClient類

@Component
public class RedisClient {
    @Autowired
    private RedisTemplate redisTemplate;
    private static final int DefaultTime = 3600; //todo
    /**
     * 添加key到redis數據庫中
     */
    public void set(String key, String value) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(key, value);
    }
    /**
     * 添加到redis 並設置過期時間 單位 秒
     *
     * @param key
     * @param value
     * @param timeOut
     * @throws Exception
     */
    public void set(String key, Object value, int timeOut)  {
        ValueOperations operations = redisTemplate.opsForValue();
        operations.set(key, Json.toJson(value));
        if (timeOut > 0) {
            redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
        }
    }
    /**
     * 取值key到redis數據庫中
     */
    public String get(String key) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }
    /**
     * 取值key到redis數據庫中
     */
    public String getObj(String key) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        if (operations == null || StringUtils.isEmpty(operations.get(key))) {
            return null;
        }
        return operations.get(key);
    }
    /**
     * 取值key到redis數據庫中
     */
    public List<Map> getList(String key) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String value = operations.get(key);
        if(StringUtils.isEmpty(value)) {
            return null;
        }
        return Json.fromJson(List.class, value);
    }
    /**
     * 刪除指定key
     */
    public void del(String key) {
        redisTemplate.delete(key);
    }
    /**
     * 保存obj對象到redis數據庫
     */
    public void setObj(Object obj) {
        ValueOperations<Object, Object> operations = redisTemplate.opsForValue();
        operations.set(obj.getClass().getName(), obj);
    }
    public void setObj(Object obj, int timeOut) throws Exception {
        ValueOperations<Object, Object> operations = redisTemplate.opsForValue();
        int times = 0;
        if (timeOut > 0) {
            times = timeOut;
        } else {
            times = DefaultTime;
        }
        operations.set(obj.getClass().getName(), obj, times, TimeUnit.SECONDS);
    }
    /**
     * 根據指定o獲取Object
     */
    public <T> T getObj(Object obj, Class<T> clazz) {
        ValueOperations<Object, Object> operations = redisTemplate.opsForValue();
        return (T) operations.get(obj.getClass().getName());
    }
    /**
     * 刪除obj對象在redis數據庫
     */
    public void delObj(Object o) {
        redisTemplate.delete(o);
    }
    /**
     * Set集合的賦值去取
     */
    public void setSetCollections(String key, Set value) {
        redisTemplate.opsForSet().add(key, value);
    }
    public String getSetCollections(String key) {
        String result = new Gson().toJson(redisTemplate.opsForSet().members(key));
        return result.substring(1, result.length() - 1);
    }
    public Set<String> getMapKeys(String key) {
        Set<String> resultMapSet = redisTemplate.opsForHash().keys(key);
        return resultMapSet;
    }
    /**
     * Map集合的賦值去取
     */
    public void setMapCollections(String key, Map<String, Object> value) {
        redisTemplate.opsForHash().putAll(key, value);
    }
    public String getMapCollections(String key) {
        return new Gson().toJson(redisTemplate.opsForHash().entries(key));
    }
    /**
     * List集合的賦值去取
     */
    public void setLists(String key, List list) {
        redisTemplate.opsForList().leftPush(key, list);
    }
    public String getListStartEnd(String key, int start, int end) {
        String result = new Gson().toJson(redisTemplate.opsForList().range(key, start, end));
        return result.substring(1, result.length() - 1);
    }
    /**
     * 查詢key的剩餘存活時間
     */
    public long getKeyExpireTime(String key) {
        return redisTemplate.getExpire(key);
    }
    /**
     * 設置key的剩餘存活時間
     */
    public boolean setKeyExpireTime(String key, int timeOut) {
        long times = 0;
        if (timeOut > 0) {
            times = timeOut * 60;
        } else {
            times = DefaultTime;
        }
        return redisTemplate.expire(key, times, TimeUnit.SECONDS);
    }
    /**
     * 判斷key是否存在
     */
    public boolean exitsKey(String key) {
        Object obj = redisTemplate.execute(new RedisCallback() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.exists(key.getBytes());
            }
        });
        boolean flag = true;
        if (obj.toString().equals("false")) {
            return false;
        }
        return flag;
    }
    /**
     * 寫入緩存設置時效時間
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;

try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章