SpringBoot 整合 SpringDataRedis

1,390 阅读5分钟

1. docker-install-redis

1. docker pull redis:latest
2. docker run  -p 6379:6379 -d --name ml-redis redis:latest redis-server --appendonly yes --requirepass password

2. add Depending

  • maven
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  • gradle
    implementation "org.springframework.boot:spring-boot-starter-data-redis"
    

3. add Config

spring:
 # redis 配置
  redis:
    # 数据库索引 (default:0)
    database: 0
    # 服务器地址 (default:localhost)
    host: 192.168.131.164
    # 服务器连接端口 (default:6379)
    port: 6379
    # 服务器连接密码 (default:空)
    password: kirito1117
    jedis:
      pool:
        # 连接池最大连接数 (default:8 , 使用负值表示没有限制)
        max-active: 8
        # 连接池最大阻塞等待时间 (default: -1 , 使用负值表示没有限制)
        max-wait: -1
        # 连接池中的最大空闲连接 (default:8)
        max-idle: 8
        # 连接池中的最小空闲连接 (default:0)
        min-idle: 0
    # 连接超时时间 (毫秒)
    timeout: 500

4. RedisTemplate Use

public class RedisController {

    @Autowired(required = false)
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("Set Value")
    @GetMapping("set")
    public void setValue(@ApiParam(value = "键", required = true) @RequestParam String key, @ApiParam(value = "值", required = true) @RequestParam String val) {
        // -----------------基础数据 类型数据操作 start--------------------
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        // String类型数据存储,不设置过期时间,永久性保存
        valueOperations.set(key, val);
        // String类型数据存储,设置过期时间为80秒,采用TimeUnit控制时间单位
        valueOperations.set(key + "_Time", val + "Time", 77, TimeUnit.SECONDS);
        // 判断key值是否存在,存在则不存储,不存在则存储
        valueOperations.setIfAbsent(key, val + "My_Redis");
        valueOperations.setIfAbsent(key + "1", "My_Redis_111");
    }

    @ApiOperation("Get Value")
    @GetMapping("get/{key}")
    public Object getValue(@ApiParam(value = "键", required = true) @PathVariable String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @ApiOperation("Remove Value")
    @DeleteMapping("remove/{key}")
    public Object removeValue(@ApiParam(value = "键", required = true) @PathVariable String key) {
        return redisTemplate.delete(key);
    }
}

5. 数据乱码配置

import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis - 配置
 *
 * @author liangzhong
 */
@Configuration
@RequiredArgsConstructor
public class RedisConfig extends CachingConfigurerSupport {

    private final RedisTemplate redisTemplate;

    /**
     * 配置Redis防止乱码
     *
     * @return
     */
    @Bean
    public RedisTemplate redisTemplateInit() {
        //设置序列化Key的实例化对象
        StringRedisSerializer stringRedisSerializer= new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //设置序列化Value的实例化对象
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        return redisTemplate;
    }
}

6. 常用接口工具类

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis 缓存 - service
 *
 * @author liangzhong.tan
 * @date 2019-12-25 11:29:27
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RedisService {

    private final RedisTemplate redisTemplate;

    /**
     * key 是否存在
     *
     * @param key
     * @return
     */
    public boolean exists(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * Set {@code value} for {@code key}, only if {@code key} does not exist.
     *
     * @param key
     * @param value
     * @param expire
     * @param timeUnit
     * @return
     */
    public boolean setNx(String key, String value, long expire, TimeUnit timeUnit) {
        try {
            return (boolean) redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(key.getBytes(), value.getBytes(), Expiration.from(expire, timeUnit), RedisStringCommands.SetOption.ifAbsent()));
        } catch (Exception e) {
            log.error("设置缓存异常, key = {}", key, e);
        }
        return false;
    }

    /**
     * Set {@code value} for {@code key}, only if {@code key} does not exist.
     *
     * @param key
     * @param value
     * @param expire 有效期.(秒)
     * @return
     */
    public boolean setNx(String key, String value, long expire) {
        try {
            return setNx(key, value, expire, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("设置缓存异常, key = {}", key, e);
        }
        return false;
    }

    /**
     * 递增 +1
     *
     * @param key
     * @return key递增后的值
     */
    public Long incrBy(String key) {
        try {
            return redisTemplate.opsForValue().increment(key);
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return null;
    }

    /**
     * 递增
     *
     * @param key
     * @param delta 步长
     * @return key递增后的值
     */
    public Long incrBy(String key, long delta) {
        try {
            return redisTemplate.opsForValue().increment(key, delta);
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return null;
    }

    /**
     * 将哈希值{@code hashKey}的{@code value}增加给定的{@code delta}。
     *
     * @param key
     * @param hashKey hashKey
     * @param delta   步长
     * @return key递增后的值
     */
    public Long hashIncrBy(String key, String hashKey, long delta) {
        try {
            return redisTemplate.opsForHash().increment(key, hashKey, delta);
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return null;
    }

    /**
     * 为 key 设置 value
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setValue(String key, Serializable value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }

    /**
     * 设置 key 的 value 和过期时间
     *
     * @param key
     * @param value
     * @param second 到期时间(秒)
     * @return
     */
    public boolean setValue(final String key, final Serializable value, final long second) {
        return setValue(key, value, second, TimeUnit.SECONDS);
    }

    /**
     * 设置 key 的 value 和过期时间
     *
     * @param key
     * @param value
     * @param expire 到期时间
     * @param unit   到期时间计量单位
     * @return
     */
    public boolean setValue(String key, Serializable value, long expire, TimeUnit unit) {
        try {
            redisTemplate.opsForValue().set(key, value, expire, unit);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }


    /**
     * 获取 key 只
     *
     * @param key
     * @return
     */
    public Object getValue(String key) {
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return null;
    }

    /**
     * 设置 key 的 value 和过期时间
     *
     * @param key
     * @param expire 到期时间
     * @param unit   到期时间计量单位
     * @return
     */
    public boolean expire(String key, long expire, TimeUnit unit) {
        try {
            redisTemplate.expire(key, expire, unit);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }

    /**
     * 设置 key 的 value 和过期时间
     *
     * @param key
     * @param expire 到期时间(秒)
     * @return
     */
    public boolean expire(final String key, final long expire) {
        return expire(key, expire, TimeUnit.SECONDS);
    }

    public Boolean setList(String key, Collection<Serializable> values) {
        try {
            redisTemplate.opsForList().leftPushAll(key, values);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }

    public <T> Boolean setList(String key, Collection<T> values, long expire) {
        try {
            redisTemplate.opsForList().leftPushAll(key, values);
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }

    public <T> boolean listAppend(final String key, T value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }

    public Boolean setHash(String key, Map<Object, Object> value) {
        try {
            redisTemplate.opsForHash().putAll(key, value);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }

    public Boolean setHash(String key, Map<Object, Object> value, long expire) {
        try {
            redisTemplate.opsForHash().putAll(key, value);
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }

    /**
     * 获取存储在{@code key}的整个哈希。
     *
     * @param key
     * @return
     */
    public Map<Object, Object> getMap(String key) {
        Map<Object, Object> v = null;
        try {
            v = redisTemplate.opsForHash().entries(key);
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return v;
    }

    /**
     * 从{@code key}处的哈希中获取给定{@code hashKey}的值。
     *
     * @param key
     * @param hashKey
     * @return
     */
    public Object getMap(String key, Object hashKey) {
        try {
            return redisTemplate.opsForHash().get(key, hashKey);
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return null;
    }

    public List<Serializable> getList(String key) {
        List<Serializable> v = null;
        try {
            v = redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return v;
    }

    public <T> List<T> getObjectList(String key) {
        List<T> v = null;
        try {
            v = redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return v;
    }


    public Boolean delete(String key) {
        try {
            redisTemplate.delete(key);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, key = {}, ex = {}", key, ex);
        }
        return false;
    }

    /**
     * 前缀匹配删除多个key
     *
     * @param keyPrefix 前缀
     * @return
     */
    public Boolean deleteLike(String keyPrefix) {
        try {
            if (StringUtils.isNotEmpty(keyPrefix)) {
                redisTemplate.delete(redisTemplate.keys(keyPrefix + "*"));
            }
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, keyPrefix = {}, ex = {}", keyPrefix, ex);
        }
        return false;
    }

    /**
     * 删除Key的集合
     *
     * @param keys
     */
    public Boolean delete(Set<String> keys) {
        try {
            redisTemplate.delete(keys);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, keys = {}, ex = {}", JSONObject.toJSONString(keys), ex);
        }
        return false;
    }

    /**
     * 删除Key的集合
     *
     * @param keys
     */
    public Boolean delete(String... keys) {
        try {
            redisTemplate.delete(keys);
            return true;
        } catch (Exception ex) {
            log.error("取缓存异常, keys = {}, ex = {}", JSONObject.toJSONString(keys), ex);
        }
        return false;
    }

    /**
     * 重名名key,如果newKey已经存在,则newKey的原值被覆盖
     *
     * @param oldKey
     * @param newKey
     */
    public void renameKey(String oldKey, String newKey) {
        redisTemplate.rename(oldKey, newKey);
    }

    /**
     * newKey不存在时才重命名
     *
     * @param oldKey
     * @param newKey
     * @return 修改成功返回true
     */
    public boolean renameKeyNotExist(String oldKey, String newKey) {
        return redisTemplate.renameIfAbsent(oldKey, newKey);
    }


    /**
     * 查询key的生命周期
     *
     * @param key
     * @param timeUnit
     * @return
     */
    public long getKeyExpire(String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }


}

7. 相关文档

Spring Data Redis Document