SpringBoot redis 简单使用

Felix 2022年06月11日 94次浏览

redis 安装

# 使用docker快速安装
# 默认配置启动
docker run --restart=always --log-opt max-size=100m --log-opt max-file=2 -p 6379:6379 --name myredis -v /root/redis/myredis/data:/data -d redis  --appendonly yes  --requirepass mypassword
# mypassword 是认证密码

# 自定义配置 myredis.conf 启动
docker run --restart=always --log-opt max-size=100m --log-opt max-file=2 -p 6379:6379 --name myredis -v /root/redis/myredis/myredis.conf:/etc/redis/redis.conf -v /root/redis/myredis/data:/data -d redis redis-server /etc/redis/redis.conf  --appendonly yes  --requirepass mypassword

SpringBoot 集成

# pom 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
# application.properties
spring.redis.host=ip
spring.redis.port=6379
spring.redis.password=mypassword
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=30000
# 调用
@Autowired
private StringRedisTemplate redisTemplate;
private static final JsonMapper mapper = new JsonMapper();
/**
* 数据缓存至redis
*
* @param key
* @param value
* @return
*/
public <K, V> void add(K key, V value) {
    try {
        if (value != null) {
            redisTemplate
                .opsForValue()
                .set(DEFAULT_KEY_PREFIX + key, value instanceof  String ? value.toString() : mapper.writeValueAsString(value));
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException("数据缓存至redis失败");
    }
}
/**
* 功能描述:Get the value of {@code key}.
*
* @param key must not be {@literal null}.
* @return java.lang.String
* @date 2021/9/19
**/
public <K> String get(K key) {
    String value;
    try {
        value = redisTemplate.opsForValue().get(DEFAULT_KEY_PREFIX + key);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException("从redis缓存中获取缓存数据失败");
    }
    return value;
}