###### Springboot整合Redis
SpringBoot操作数据:spring-data jpa jdbc mongodb redis!
SpringData也是和SpringBoot齐名的项目!
说明:在SpringBoot2.X之后,原本使用的jedis被替换为lettuce?
jedis: 采用的是直连,多个线程的话,是不安全的,如果想要避免不安全,使用jedis pool连接池! BIO
lettuce: 采用netty ,实例可以再多个线程中进行共享,不存在线程不安全的情况! 可以减少线程数据了。更像Nio模式
源码分析:
```java
@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"} // 我们可以自己定义一个redisTemplate来替换这个默认的
)
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 默认的RedisTemplate 没有过多的设置,redis对象都是需要序列化!Dubbo
// 两个泛型都是Object, Object 的类型,我们使用后需要强制转换<String,Object>
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class) // 由于String 是redis中最常使用的类型,所以说单独提出来了一个bean!
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
整合测试:
1.导入依赖
<!--操作redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置连接
# SpringBoot 所有的配置类,都有一个自动配置类 RedisAutoConfiguration
# 自动配置类都会绑定一个properties 配置文件 RedisProperties
spring.redis.host=127.0.0.1
spring.redis.port=6379
3.测试
package com.spring;
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.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class RedisSpingbootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
// redisTemplate 操作不同的数据类型 api和我们的指令是一样的
// opsForValue来操作 字符串 类似于String
// opsForList 操作List 类似于String
// opsForSet
// opsForHash
// opsForZSet
// opsForGeo
// opsForHyperLogLog
// 除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作
// 比如事务,和基本的CRUD
// 获取redis连接对象
/* RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.flushAll();
connection.flushDb();*/
redisTemplate.opsForValue().set("mykey","二狗子");
System.out.println(redisTemplate.opsForValue().get("mykey"));
}
}
关于对象的 保存:所有的对象需要序列化
自定义的RedisTemplate
package com.spring.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
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;
RedisConfig
/**
* @author 86182
*/
@Configuration
@SuppressWarnings("all")
public class RedisConfig {
@Bean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 我们为了开发方便,一般直接使用<String, Object>
RedisTemplate<String, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
// Json序列化配置
Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
objectJackson2JsonRedisSerializer.setObjectMapper(om);
// String 的序列化配置
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key 采用String的序列化
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化
template.setHashKeySerializer(stringRedisSerializer);
// value序列化采用jackon
template.setValueSerializer(objectJackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(objectJackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
RedisTemplate工具类
import com.google.gson.Gson;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author czq
* @date 2020-5-17
*/
@Component
@SuppressWarnings("all")
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
// 默认过期时间 单位:秒 一天过期
public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
// 时间单位 默认秒 timeUnit
public static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// json 格式化工具
public static final Gson GSON = new Gson();
// 基础 ----------------------- start --------------------------
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return true / false
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TIME_UNIT);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据 key 获取过期时间
*
* @param key 键
* @return
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TIME_UNIT);
}
/**
* 判断 key 是否存在
*
* @param key 键
* @return true / false
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 键(一个或者多个)
*/
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
// 传入一个 Collection<String> 集合
List keys = CollectionUtils.arrayToList(key);
redisTemplate.delete(keys);
}
}
}
/**
* Object 转成 JSON 数据
*
* @param object
* @return
*/
private String toJson(Object object) {
boolean flag = object instanceof Integer || object instanceof Long || object instanceof Float ||
object instanceof Double || object instanceof Boolean || object instanceof String;
if (flag) {
return String.valueOf(object);
}
return GSON.toJson(object);
}
/**
* JSON 数据,转成 Object
*
* @param json
* @param clazz
* @param <T>
* @return
*/
private <T> T fromJson(String json, Class<T> clazz) {
return GSON.fromJson(json, clazz);
}
// 基础 ----------------------- end --------------------------
// String ----------------------- start --------------------------
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true / false
*/
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 时间(秒),如果 time < 0 则设置无限时间
* @return true / false
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TIME_UNIT);
} else {
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().increment(key, delta);
}
// String ----------------------- end --------------------------
// Hash ----------------------- start --------------------------
/**
* HashGet
*
* @param key 键(no null)
* @param item 项(no null)
* @return 值
*/
public Object hGet(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取 key 对应的 map
*
* @param key 键(no null)
* @return 对应的多个键值
*/
public Map<Object, Object> hmGet(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 值
* @return true / false
*/
public boolean hmSet(String key, Map<Object, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 值
* @param time 时间
* @return true / false
*/
public boolean hmSet(String key, Map<Object, 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 值
* @param time 时间(如果原来的 Hash表 设置了时间,这里会覆盖)
* @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 项(可以多个,no null)
*/
public void hDel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断 Hash 表 中是否有该键的值
*
* @param key 键(no null)
* @param item 值(no null)
* @return true / false
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* Hash 递增,如果不存在则创建一个,并把新增的值返回
*
* @param key 键
* @param item 项
* @param by 递增大小 > 0
* @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);
}
// Hash ----------------------- end --------------------------
// Set ----------------------- start --------------------------
/**
* 根据 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 的 set 中,根据 value 查询是否存在
*
* @param key 键
* @param value 值
* @return true / false
*/
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 values 值(可以多个)
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将数据放入 set 缓存,并设置时间
*
* @param key 键
* @param time 时间
* @param values 值(可以多个)
* @return 成功放入个数
*/
public long sSet(String key, long time, Object... values) {
try {
long count = redisTemplate.opsForSet().add(key, values);
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;
}
}
/**
* 移除 set 缓存中,值为 value 的
*
* @param key 键
* @param values 值
* @return 成功移除个数
*/
public long setRemove(String key, Object... values) {
try {
return redisTemplate.opsForSet().remove(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// Set ----------------------- end --------------------------
// List ----------------------- start --------------------------
/**
* 获取 list 缓存的内容
*
* @param key 键
* @return
*/
public List<Object> lGet(String key) {
try {
final long START_INDEX = 0;
final long END_INDEX = 0;
return redisTemplate.opsForList().range(key, START_INDEX, END_INDEX);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取 list 缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束(0 到 -1 代表所有值)
* @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;
}
}
/**
* 根据索引 index 获取键为 key 的 list 中的元素
*
* @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;
}
}
/**
* 将值 value 插入键为 key 的 list 中,如果 list 不存在则创建空 list
*
* @param key 键
* @param value 值
* @return true / false
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将值 value 插入键为 key 的 list 中,并设置时间
*
* @param key 键
* @param value 值
* @param time 时间
* @return true / false
*/
public boolean lSet(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;
}
}
/**
* 将 values 插入键为 key 的 list 中
*
* @param key 键
* @param values 值
* @return true / false
*/
public boolean lSetList(String key, List<Object> values) {
try {
redisTemplate.opsForList().rightPushAll(key, values);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将 values 插入键为 key 的 list 中,并设置时间
*
* @param key 键
* @param values 值
* @param time 时间
* @return true / false
*/
public boolean lSetList(String key, List<Object> values, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, values);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引 index 修改键为 key 的值
*
* @param key 键
* @param index 索引
* @param value 值
* @return true / false
*/
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;
}
}
/**
* 在键为 key 的 list 中删除值为 value 的元素
*
* @param key 键
* @param count 如果 count == 0 则删除 list 中所有值为 value 的元素
* 如果 count > 0 则删除 list 中最左边那个值为 value 的元素
* 如果 count < 0 则删除 list 中最右边那个值为 value 的元素
* @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;
}
}
// List ----------------------- end --------------------------
}
所有的redis操作,其实对于java开发来说,十分简单,重要的是要理解redis的思想和每一种数据结构的用处和
);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 在键为 key 的 list 中删除值为 value 的元素
*
* @param key 键
* @param count 如果 count == 0 则删除 list 中所有值为 value 的元素
* 如果 count > 0 则删除 list 中最左边那个值为 value 的元素
* 如果 count < 0 则删除 list 中最右边那个值为 value 的元素
* @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;
}
}
// List ----------------------- end --------------------------
}
所有的redis操作,其实对于java开发来说,十分简单,重要的是要理解redis的思想和每一种数据结构的用处和
作用场景!