一、redis简介
Redis(官网:Redis) 是一个高性能的key-value数据库。redis提供五种数据类型:string,list,set及zset(sorted set),hash。其大多数使用场景为缓存,在分布式场景下可以用于解决分布式事务。
二、redis的安装与配置
推荐使用docker安装。前提条件先安装docker,关于docker的讲解本文就不详细介绍,在"/"根目录下创建doker目录,再创建redis目录,结构如下图:
准备redis.conf配置文件和redis-start.sh启动脚本,data为挂载数据的目录,启动后自动生成。
redis.conf详情
daemonize no ---是否要用守护线程的方式启动 默认no
port 6379 ---端口 默认6379
bind 0.0.0.0 ---绑定到0.0.0.0那么所有机器上的地址都可以访问服务,
如果绑定到特定的ip那么只能是特定
的ip能够到达redis服务。
appendonly yes ---持久化配置
redis-start.sh详情
#!/bin/bash
docker rm -f redis
docker run -d -p 6379:6379 \
--name redis \
-v /docker/redis/redis.conf:/etc/redis/redis.conf \
-v /docker/redis/data:/data \
--restart=always \
redis redis-server /etc/redis/redis.conf
注意:创建 redis-start.sh文件后使用 chmod +x redis-start.sh 增加可执行权限。
启动redis直接执行命令:"./redis-start.sh",docker会自动删除原来的镜像再拉去指定的镜像启动。
执行docker ps 查询redis启动状态或者使用docker logs redis(容器id)查询启动日志观察redis是否启动成功!
使用docker logs查询启动日志如图:
使用docker ps查询redis 启动状态如图:
自此redis的安装与配置完毕。
特别提醒:云服务器需要在控制台修改安全组策略开放6379端口让外部可以访问服务器上的redis服务。
三、spring boot项目使用redis
1.创建spring boot 项目
选择路径填写项目信息,选择项目依赖。
创建完成后带maven加载完毕项目结构如下图:
2.修改配置文件和新增配置类
如何配置?比如我怎么知道该配什么?
去看spring-autoconfigure-metadata.properties redis相关的为"RedisAutoConfiguration"。同理可查询其余配置类。
配置详解:
RedisProperties.class就是配置了连接redis需要配置什么,有些属性有默认值,不配置就是使用在里面配置的默认值。也给我们提供了一个操作对象redisTemplate,这个就是java操作redis的模板对象,但是我们需要RedisConfig做一点小小的配置来是redisTemplate更加方便。
个人比较喜欢yml配置
spring:
redis:
port: 6379
host: 127.0.0.1 --改为服务器地址
redis配置类方便注入配置好的redisTemplate ,主要配置了redis key 和 value 序列化方式方式,避免乱码。
package com.example.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 直接使用 <String,Object>,避免类型转换
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// ===== 序列化设置 =====
// --------------- Jackson 序列化 -----------------
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 替换enableDefaultTyping方法
objectMapper.activateDefaultTyping(
LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.WRAPPER_ARRAY);
// 设置对象映射
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// --------------- String 序列化 -----------------
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// ===== RedisTemplate 序列化设置 =====
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hashKey采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value采用Jackson的序列化方式
template.setValueSerializer(jackson2JsonRedisSerializer);
// HashValue采用Jackson的序列化方式
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
至此整合配置完毕!接下来进行简单的存取操作。
3.注入使用
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class RedisApplicationTests {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
void contextLoads() {
redisTemplate.opsForValue().set("name", "hello ",100, TimeUnit.SECONDS);
System.out.println(redisTemplate.opsForValue().get("name"));
}
}
为了方便使用我封装了一个RedisUtil对几种数据类型的操作都有封装,需要的朋友自提!
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
@SuppressWarnings("all")
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
//===============================================================
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键
* @return 时间(秒) 0 代表永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断键是否存在
*
* @param key 键
* @return true 存在 false 不纯在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个或者多个key
*/
public void delKeys(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(Arrays.asList(key));
}
}
}
//=============================String==================================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存存放
*
* @param key 键
* @param value 值
* @return
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存存放
*
* @param key 键
* @param value 值
* @param time 缓存时间 必须大于0
* @return true 成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param delta 递增因子
* @return 当前数值
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 递减因子
* @return 当前数值
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().decrement(key, delta);
}
//=============================Map==================================
/**
* HashGet
*
* @param key 键
* @param item 项
* @return
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取HashKey 对应的所有值
*
* @param key 键
* @return 对应的多个值
*/
public Map<Object, Object> mhget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 设置多个值
*
* @param key
* @param map
* @return
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 设置多个值并设置过期时间
*
* @param key
* @param map
* @param time
* @return
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表存放数据
*
* @param key 键
* @param item 项
* @param value 值
* @return 成功返回true 失败 false
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表存放数据
*
* @param key 键
* @param item 项
* @param value 值
* @return 成功返回true 失败 false
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键
* @param item 项
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否存在该项值
*
* @param key
* @param item
* @return
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash 递增 如果不存在会创建
*
* @param key
* @param item
* @param by
* @return 增加后的值
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash 递减
*
* @param key
* @param item
* @param by
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
//=============================Set==================================
/**
* 根据key获取Set中的值
*
* @param key
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据key value 判断Set 中是否存在该值
*
* @param key 键
* @param value 值
* @return
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据存放Set 中
*
* @param key 键
* @param value 值
* @return 成功的个数
*/
public long sSet(String key, Object... value) {
try {
return redisTemplate.opsForSet().add(key, value);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将数据存放Set 中
*
* @param key 键
* @param value 值
* @param time key过期时间
* @return 成功的个数
*/
public long sSet(String key, long time, Object... value) {
try {
Long count = redisTemplate.opsForSet().add(key, value);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set 缓存值的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value 的
*
* @param key 键
* @param value 值
* @return 移除的个数
*/
public long setRemove(String key, Object... value) {
try {
return redisTemplate.opsForSet().remove(key, value);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//=============================Set==================================
/**
* 获取list缓存
*
* @param key 键
* @param start 开始值
* @param end 结束值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list 长度
*
* @param key
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取指定索引的值
*
* @param key 键
* @param index 索引 当index >=0 时 0-》表头 1->第二个元素 ;当index <0 时 -1表尾 -2第二个元素
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 从左边放入一个
*
* @param key 键
* @param value 值
* @return
*/
public boolean lpust(String key, Object value) {
try {
redisTemplate.opsForList().leftPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 从左边放入一个
*
* @param key 键
* @param value 值
* @param time 过期时间
* @return
*/
public boolean lpust(String key, Object value, long time) {
try {
redisTemplate.opsForList().leftPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 从右边放入一个
*
* @param key 键
* @param value 值
* @return
*/
public boolean rpust(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 从右边放入一个
*
* @param key 键
* @param value 值
* @param time 过期时间
* @return
*/
public boolean rpust(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list 放入缓存
*
* @param key
* @param value
* @return
*/
public boolean rpushAll(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list 放入缓存并设置过期时间
*
* @param key
* @param value
* @return
*/
public boolean rpushAll(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改值
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除数量
* @param value 值
* @return 成功移除数量
*/
public long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
以上就是spring boot 整合redis 的简单案例,关于redis的更多高级用法和redis的持久化和redis的同步机制,redis集群搭建,以及redis穿透、击穿、雪崩等解决方案会在后续文章陆续更新。
有疑问的朋友欢迎留言,大家一起交流学习。