SpringBoot:Redis整合
收起目录-
1、新建工程、导入依赖
说明:
pom.xml参考
2、配置链接
3、测试
4、key,value乱码问题
问题:
原因:
解决办法:
5、Redis客户端中文乱码
6、自定义RedisTemplate
7、RedisUtils类
8、再次测试
1、新建工程、导入依赖
说明:
spring2.X之后,底层原来使用的jedis被替换为了lettuce
jedis:采用直连,多个线程操作是不安全的,要避免不安全,需要使用jedis pool间接持,更像BIO模式
lettuce:采用netty,实例可以在多个线程**享,不存在线程不安全的情况,可以减少线程数量,更新NIO模式
pom.xml参考
<?xml version="1.0" encoding="UTF-8"?>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.5.3
com.lu
springboot-redis
0.0.1-SNAPSHOT
springboot-redis
Demo project for Spring Boot
<java.version>1.8</java.version>
<repackage.classifier/>
<spring-native.version>0.10.2</spring-native.version>
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-web
org.springframework.experimental
spring-native
s
p
r
i
n
g
−
n
a
t
i
v
e
.
v
e
r
s
i
o
n
<
/
v
e
r
s
i
o
n
>
<
/
d
e
p
e
n
d
e
n
c
y
>
<
d
e
p
e
n
d
e
n
c
y
>
<
g
r
o
u
p
I
d
>
o
r
g
.
s
p
r
i
n
g
f
r
a
m
e
w
o
r
k
.
b
o
o
t
<
/
g
r
o
u
p
I
d
>
<
a
r
t
i
f
a
c
t
I
d
>
s
p
r
i
n
g
−
b
o
o
t
−
d
e
v
t
o
o
l
s
<
/
a
r
t
i
f
a
c
t
I
d
>
<
s
c
o
p
e
>
r
u
n
t
i
m
e
<
/
s
c
o
p
e
>
<
o
p
t
i
o
n
a
l
>
t
r
u
e
<
/
o
p
t
i
o
n
a
l
>
<
/
d
e
p
e
n
d
e
n
c
y
>
<
d
e
p
e
n
d
e
n
c
y
>
<
g
r
o
u
p
I
d
>
o
r
g
.
s
p
r
i
n
g
f
r
a
m
e
w
o
r
k
.
b
o
o
t
<
/
g
r
o
u
p
I
d
>
<
a
r
t
i
f
a
c
t
I
d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
d
>
o
r
g
.
p
r
o
j
e
c
t
l
o
m
b
o
k
<
/
g
r
o
u
p
I
d
>
<
a
r
t
i
f
a
c
t
I
d
>
l
o
m
b
o
k
<
/
a
r
t
i
f
a
c
t
I
d
>
<
/
e
x
c
l
u
d
e
>
<
/
e
x
c
l
u
d
e
s
>
<
c
l
a
s
s
i
f
i
e
r
>
{spring-native.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> <classifier>
spring−native.version</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring−boot−devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring−boot−configuration−processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring−boot−starter−test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring−boot−maven−plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes><classifier>{repackage.classifier}
paketobuildpacks/builder:tiny
<BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
org.springframework.experimental
spring-aot-maven-plugin
s
p
r
i
n
g
−
n
a
t
i
v
e
.
v
e
r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
r
l
>
h
t
t
p
s
:
/
/
r
e
p
o
.
s
p
r
i
n
g
.
i
o
/
r
e
l
e
a
s
e
<
/
u
r
l
>
<
s
n
a
p
s
h
o
t
s
>
<
e
n
a
b
l
e
d
>
f
a
l
s
e
<
/
e
n
a
b
l
e
d
>
<
/
s
n
a
p
s
h
o
t
s
>
<
/
p
l
u
g
i
n
R
e
p
o
s
i
t
o
r
y
>
<
/
p
l
u
g
i
n
R
e
p
o
s
i
t
o
r
i
e
s
>
<
!
−
−
报
错
了
,
等
空
了
研
究
下
−
−
>
<
!
−
−
<
p
r
o
f
i
l
e
s
>
<
p
r
o
f
i
l
e
>
<
i
d
>
n
a
t
i
v
e
<
/
i
d
>
<
p
r
o
p
e
r
t
i
e
s
>
<
r
e
p
a
c
k
a
g
e
.
c
l
a
s
s
i
f
i
e
r
>
e
x
e
c
<
/
r
e
p
a
c
k
a
g
e
.
c
l
a
s
s
i
f
i
e
r
>
<
n
a
t
i
v
e
−
b
u
i
l
d
t
o
o
l
s
.
v
e
r
s
i
o
n
>
0.9.1
<
/
n
a
t
i
v
e
−
b
u
i
l
d
t
o
o
l
s
.
v
e
r
s
i
o
n
>
<
/
p
r
o
p
e
r
t
i
e
s
>
<
d
e
p
e
n
d
e
n
c
i
e
s
>
<
d
e
p
e
n
d
e
n
c
y
>
<
g
r
o
u
p
I
d
>
o
r
g
.
g
r
a
a
l
v
m
.
b
u
i
l
d
t
o
o
l
s
<
/
g
r
o
u
p
I
d
>
<
a
r
t
i
f
a
c
t
I
d
>
j
u
n
i
t
−
p
l
a
t
f
o
r
m
−
n
a
t
i
v
e
<
/
a
r
t
i
f
a
c
t
I
d
>
<
v
e
r
s
i
o
n
>
{spring-native.version}</version> <executions> <execution> <id>test-generate</id> <goals> <goal>test-generate</goal> </goals> </execution> <execution> <id>generate</id> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <repositories> <repository> <id>spring-releases</id> <name>Spring Releases</name> <url>https://repo.spring.io/release</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-releases</id> <name>Spring Releases</name> <url>https://repo.spring.io/release</url> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> <!--报错了,等空了研究下--> <!--<profiles> <profile> <id>native</id> <properties> <repackage.classifier>exec</repackage.classifier> <native-buildtools.version>0.9.1</native-buildtools.version> </properties> <dependencies> <dependency> <groupId>org.graalvm.buildtools</groupId> <artifactId>junit-platform-native</artifactId> <version>
spring−native.version</version><executions><execution><id>test−generate</id><goals><goal>test−generate</goal></goals></execution><execution><id>generate</id><goals><goal>generate</goal></goals></execution></executions></plugin></plugins></build><repositories><repository><id>spring−releases</id><name>SpringReleases</name><url>https://repo.spring.io/release</url><snapshots><enabled>false</enabled></snapshots></repository></repositories><pluginRepositories><pluginRepository><id>spring−releases</id><name>SpringReleases</name><url>https://repo.spring.io/release</url><snapshots><enabled>false</enabled></snapshots></pluginRepository></pluginRepositories><!−−报错了,等空了研究下−−><!−−<profiles><profile><id>native</id><properties><repackage.classifier>exec</repackage.classifier><native−buildtools.version>0.9.1</native−buildtools.version></properties><dependencies><dependency><groupId>org.graalvm.buildtools</groupId><artifactId>junit−platform−native</artifactId><version>{native-buildtools.version}
test
org.graalvm.buildtools
native-maven-plugin
${native-buildtools.version}
test-native
test
test
build-native
package
build
–>
2、配置链接
spring.redis.host=127.0.0.1
spring.redis.port=6379
或者
spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis服务器连接密码(默认为空)
spring.redis.password=
#连接池最大连接数(使用负值表示没有限制)
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
3、测试
package com.lu;
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 SpringbootRedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
// redisTemplate 操作不同的数据类型,api和我们的指令是一样的
// opsForValue 操作字符串,类似String
// opsForList 操作list,类似List
// opsForSet
// opsForHash
// opsForZSet
// opsForGeo
// opsForHyperLogLog
// 除了基本的操作,我们常用的方法可以直接通过redisTemplate操作,比如事务,和基本的CRUD
//获取redis的链接对象
// RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
// connection.flushDb();
// connection.flushAll();
redisTemplate.opsForValue().set(“myKey”, “myValue”);
System.out.println(redisTemplate.opsForValue().get(“myKey”));
}
}
4、key,value乱码问题
问题:
存值的时候,如果不先进行序列化,虽然在程序中能正常读取,但是在客户端中查看会存在乱码的问题,如下
原因:
spring-data-redis的RedisTemplate<K, V>模板类在操作redis时默认使用JdkSerializationRedisSerializer来进行序列化,这种方式似乎会导致序列化出现乱码,需要修改序列化的方式
解决办法:
//序列化对象
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);
//String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
具体代码会在后面自定义RedisTemplate中体现
5、Redis客户端中文乱码
解决办法:
命令行输入chcp 65001(utf-8编码),然后在命令行输入 redis-cli --raw 打开客户端就能正常显示了
6、自定义RedisTemplate
springboot的所有配置类,都有一个自动配置类:RedisAutoConfiguration
自动配置文件都会绑定一个properties配置文件:RedisProperties
源码分析:
@Bean
@ConditionalOnMissingBean(name = “redisTemplate”)//我们可以自定义一个redisTemplate来替换这个默认的
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
//默认的RedisTemplate没有过多的设置,对象都是需要序列化的
//两个泛型都是Object,Object 的类型,我们后续使用需要强制转换<String,Object>
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean//由于String是redis中最常用的类型,所以单独提出来了一个bean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
我们可以自定义一个redisTemplate来替换这个默认的redisTemplate
RedisConfig.java
package com.lu.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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 {
//固定模板
//自己定义了一个RedisTemplate
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
// 我们为了自己开发方便,一般直接使用<String,Object>
RedisTemplate<String,Object> template = new RedisTemplate<String,Object>();
template.setConnectionFactory(factory);
//序列化对象
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);
//String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
7、RedisUtils类
package com.lu.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// =common
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
/
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 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/*
* 判断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 可以传一个值 或多个
/
@SuppressWarnings(“unchecked”)
public void del(String… key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection) CollectionUtils.arrayToList(key));
}
}
}
// String=
/*
* 普通缓存获取
* @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 如果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 {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
* 递增
* @param key 键
* @param delta 要增加几(大于0)
/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException(“递增因子必须大于0”);
}
return redisTemplate.opsForValue().increment(key, delta);
}
/*
* 递减
* @param key 键
* @param delta 要减少几(小于0)
/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException(“递减因子必须大于0”);
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// Map=
/*
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/*
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/*
* HashSet
* @param key 键
* @param map 对应多个键值
/
public boolean hmset(String key, Map<String, 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<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 值
* @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 键 不能为null
* @param item 项 可以使多个 不能为null
/
public void hdel(String key, Object… item) {
redisTemplate.opsForHash().delete(key, item);
}
/*
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为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)
/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/*
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// set=
/*
* 根据key获取Set中的所有值
* @param key 键
/
public Set sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*
* 根据value从一个set中查询,是否存在
*
* @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 sSetAndTime(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 键
/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/*
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
/
public long setRemove(String key, Object… values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// =list===
/*
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
/
public List 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 键
/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/*
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0
时,-1,表尾,-2倒数第二个元素,依次类推
/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*
* 将list放入缓存
*
* @param key 键
* @param value 值
/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
/
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;
}
}
/*
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
/
public boolean lSet(String key, List value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
/
public boolean lSet(String key, List value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
* 根据索引修改list中的某条数据
*
* @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 {
Long remove = redisTemplate.opsForList().remove(key, count,
value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
8、再次测试
新增User实体类
package com.lu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
//在企业中,我们所有的pojo都需要序列化
public class User implements Serializable {
private String name;
private int age;
}
测试代码
@Test
public void test() throws JsonProcessingException {
//真实开发一般用json来传递对象
User user = new User(“张三”,33);
//String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set(“user”,user);
System.out.println(“key:user,value:” + redisTemplate.opsForValue().get(“user”));
//用自己封装的工具来操作,简化代码
User user2 = new User(“李四”,33);
redisUtils.set(“user2”, user2);
System.out.println(“key:user2,value:” + redisUtils.get(“user2”));
redisUtils.set(“myKey”, “我是中文字符串内容”);
System.out.println(“key:myKey,value:” + redisUtils.get(“myKey”));
}