SpringBoot集成Redis

2019-08-07  本文已影响0人  陽_young

1.pom引用

<!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>RELEASE</version>
        </dependency>

2.config


@Configuration
@ConditionalOnProperty(value="redis.config.host")
public class RedisConfig extends CachingConfigurerSupport {

    @Autowired
    private RedisBean redisBean;

    @Bean
    public RedisService gerRedisService(){
        return new RedisService(redisTemplate(redisConnectionFactory()));
    }

    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redisBean.getHost());
        factory.setPort(redisBean.getPort());
        factory.setTimeout(redisBean.getTimeout()); //设置连接超时时间
        factory.setPassword(redisBean.getPassword());
        factory.setDatabase(redisBean.getDbIndex());
        return factory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
        template.afterPropertiesSet();
        return template;
    }
    
    private void setSerializer(StringRedisTemplate template) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
    }
}

3.application.yml配置
*若设置密码,需在redis.windows-service.conf文件中修改requirepass 属性

redis:
  config:
    host: 127.0.0.1
    port: 6379
    timeout: 1000
   # password: 123456
    minIdle: 0
    maxIdle: 10
    maxActive: 200
    maxWait: -1

4.工具类


public class RedisService {
    private RedisTemplate redisTemplate;

    public RedisService(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }


    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 写入缓存设置时效时间
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime , TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value,expireTime,timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 批量删除对应的value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0){
            redisTemplate.delete(keys);
        }
    }
    /**
     * 删除对应的value
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     * 读取缓存
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }
    
    /**
     * 哈希删除
     * 
     * @param key
     * @param hashKey
     */
    public void hDel(String key, Object hashKey){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.delete(key, hashKey);
    }
    
    public void hmPutAll(String key, Map<? extends Object,? extends Object> map){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.putAll(key, map);
    }
    
    public HashOperations<String, Object, Object> hashOperate(){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash;
    }
    /**
     * 哈希获取数据
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }

    /**
     * 哈希获取所有数据
     * @param key
     * @return
     */
    public Map<? extends Object,? extends Object> hmGetAll(String key){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.entries(key);
    }

    /**
     * 列表添加
     * @param k
     * @param v
     */
    public void lPush(String k,Object v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.leftPush(k,v);
    }
    
    
    /**
     * 列表添加
     * @param k
     * @param v
     */
    public void lPush(String k,Object... v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.leftPushAll(k,v);
    }
    
    /**
     * 列表移除
     * @param k
     * @param v
     */
    public Object lPop(String k){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.leftPop(k);
    }
    
    public Long lSize(String k){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.size(k);
    }

    /**
     * 列表获取
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }

    /**
     * 集合添加
     * @param key
     * @param value
     */
    public void setAdd(String key,Object... value){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key,value);
    }
    
    /**
     * 集合移除
     * @param key
     * @param value
     */
    public void setRemove(String key,Object... value){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.remove(key,value);
    }

    /**
     * 集合获取
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }
    
    /**
     * 集合获取
     * @param key
     * @return
     */
    public Boolean setIsMember(String key,Object o){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.isMember(key, o);
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key,Object value,double scoure){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }

    /**
     * 有序集合获取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
    
    /**
     * 获取过期时间
     * @param key
     * @param timeUnit 时间单位:秒、毫秒等
     * @return
     */
    public Long getExpire(String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }
    
    /**
     * 设置过期时间,单位秒
     * @param key
     * @param timeout
     * @return
     */
    public boolean setExpire(String key, long timeout) {
        return redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }
    
    /**
     * 从集合中删除指定个数的value
     * @param key
     * @param count 个数
     * @param value 数值
     * @return
     */
    public Long lrem(String key, long count, Object value) {
        return redisTemplate.opsForList().remove(key, count, value);
    }
    
    public boolean setIfAbsent(String key, Object value) {
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        return operations.setIfAbsent(key, value);
    }
    
    public Object getAndSet(String key, Object value) {
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        return operations.getAndSet(key, value);
    }
}
上一篇下一篇

猜你喜欢

热点阅读