赞
踩
1:导入相关依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.xxy</groupId> <artifactId>redis-java</artifactId> <version>0.0.1-SNAPSHOT</version> <name>redis-java</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.16</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2:配置application.yml
server: port: 8000 spring: redis: host: localhost port: 6379 timeout: 5000 password: 123456 jedis: pool: max-active: 8 max-wait: -1 max-idle: 8 min-idle: 0
3:Redis配置类
package com.xxy.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; /** * @author 兴跃 * Redis配置类 */ @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { 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); 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; } }
4:Redis工具类
package com.xxy.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; 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; /** * @author 兴跃 */ @Component public class RedisUtils { @Autowired private RedisTemplate redisTemplate; /*************************************key的一系列操作*******************************************/ /** * 直接写入缓存 */ public boolean set(final String key, Object value) { try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * 写入并设置过期时间 * * @param key * @param value * @param expireTime * @param timeUnit * @return */ public boolean set(final String key, Object value, long expireTime, TimeUnit timeUnit) { try { ValueOperations operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, timeUnit); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 指定key到期时间 * * @param key * @param time * @param timeUnit * @return */ public boolean expire(String key, long time, TimeUnit timeUnit) { try { if (time > 0) { redisTemplate.expire(key, time, timeUnit); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除key的过期时间,key将要持久保持 * * @param key * @return */ public boolean persist(String key) { return redisTemplate.persist(key); } /** * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0或-1代表为永久有效 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void remove(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } /** * 判断缓存中是否存在该key对应的value * * @param key * @return */ public boolean hasKey(final String key) { return redisTemplate.hasKey(key); } /** * 普通根据key获取 * * @param key * @return */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 序列化key * * @param key * @return */ public byte[] dump(String key) { return redisTemplate.dump(key); } /** * 从当前数据库中随机返回一个 key * * @return */ public String randomKey() { return redisTemplate.randomKey().toString(); } /** * 修改 key 的名称 * * @param oldKey * @param newKey */ public void rename(String oldKey, String newKey) { redisTemplate.rename(oldKey, newKey); } /** * 仅当 newkey 不存在时,将 oldKey 改名为 newkey * * @param oldKey * @param newKey * @return */ public Boolean renameIfAbsent(String oldKey, String newKey) { return redisTemplate.renameIfAbsent(oldKey, newKey); } /** * 返回 key 所储存的值的类型 * * @param key * @return */ public DataType type(String key) { return redisTemplate.type(key); } /** * 获取所保存的字符的长度 * * @param key * @return */ public Long size(String key) { return redisTemplate.opsForValue().size(key); } /** * 批量添加 * * @param maps */ public void multiSet(Map<String, String> maps) { redisTemplate.opsForValue().multiSet(maps); } /** * 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在 * * @param maps * @return 之前已经存在返回false, 不存在返回true */ public boolean multiSetIfAbsent(Map<String, String> maps) { return redisTemplate.opsForValue().multiSetIfAbsent(maps); } /** * 增加(自增长), 负数则为自减 * * @param key * @return */ public Long incrBy(String key, long increment) { return redisTemplate.opsForValue().increment(key, increment); } /** * 追加到末尾 * * @param key * @param value * @return */ public Integer append(String key, String value) { return redisTemplate.opsForValue().append(key, value); } /*************************************hash的一系列操作*******************************************/ /** * 往hash中保存数据 * * @param key * @param hKey * @param value */ public void hPut(final String key, final String hKey, final Object value) { redisTemplate.opsForHash().put(key, hKey, value); } /** * 往hash表中存多个数据 * * @param key * @param maps */ public void hPutAll(String key, Map<String, String> maps) { redisTemplate.opsForHash().putAll(key, maps); } /** * 获取hash表中的数据 * * @param key * @param hKey * @return */ public Object hGet(final String key, final String hKey) { return redisTemplate.opsForHash().get(key, hKey); } /** * 获取多个Hash中的数据 * * @param key Redis键 * @param hKeys Hash键集合 * @return Hash对象集合 */ public List<Object> hMultiGet(final String key, final Collection<Object> hKeys) { return redisTemplate.opsForHash().multiGet(key, hKeys); } /** * 获取所有哈希表中的字段 * * @param key * @return */ public Set<Object> hKeys(String key) { return redisTemplate.opsForHash().keys(key); } /** * 获取哈希表中字段的数量 * * @param key * @return */ public Long hSize(String key) { return redisTemplate.opsForHash().size(key); } /** * 获取哈希表中所有值 * * @param key * @return */ public List<Object> hValues(String key) { return redisTemplate.opsForHash().values(key); } /*************************************set的一系列操作*******************************************/ /** * 往Set中存入数据 * * @param key Redis键 * @param values 值 * @return 存入的个数 */ public long sSet(final String key, final Object... values) { Long count = redisTemplate.opsForSet().add(key, values); return count == null ? 0 : count; } /** * 删除Set中的数据 * * @param key Redis键 * @param values 值 * @return 移除的个数 */ public long setDel(final String key, final Object... values) { Long count = redisTemplate.opsForSet().remove(key, values); return count == null ? 0 : count; } /** * 获取集合的大小 * * @param key * @return */ public Long sSize(String key) { return redisTemplate.opsForSet().size(key); } /** * 判断集合是否包含value * * @param key * @param value * @return */ public Boolean sIsMember(String key, Object value) { return redisTemplate.opsForSet().isMember(key, value); } /** * 获取两个集合的交集 * * @param key * @param otherKey * @return */ public Set<String> sIntersect(String key, String otherKey) { return redisTemplate.opsForSet().intersect(key, otherKey); } /** * 获取key集合与多个集合的交集 * * @param key * @param otherKeys * @return */ public Set<String> sIntersect(String key, Collection<String> otherKeys) { return redisTemplate.opsForSet().intersect(key, otherKeys); } /** * 获取两个集合的并集 * * @param key * @param otherKeys * @return */ public Set<String> sUnion(String key, String otherKeys) { return redisTemplate.opsForSet().union(key, otherKeys); } /** * 获取key集合与多个集合的并集 * * @param key * @param otherKeys * @return */ public Set<String> sUnion(String key, Collection<String> otherKeys) { return redisTemplate.opsForSet().union(key, otherKeys); } /** * 获取集合所有元素 * * @param key * @return */ public Set<String> setMembers(String key) { return redisTemplate.opsForSet().members(key); } /*************************************list的一系列操作*******************************************/ /** * 往List中存入数据 * * @param key Redis键 * @param value 数据 * @return 存入的个数 */ public long listPush(final String key, final Object value) { Long count = redisTemplate.opsForList().rightPush(key, value); return count == null ? 0 : count; } /** * 往List中存入多个数据 * * @param key Redis键 * @param values 多个数据 * @return 存入的个数 */ public long listPushAll(final String key, final Collection<Object> values) { Long count = redisTemplate.opsForList().rightPushAll(key, values); return count == null ? 0 : count; } /** * 往List中存入多个数据 * * @param key Redis键 * @param values 多个数据 * @return 存入的个数 */ public long listPushAll(final String key, final Object... values) { Long count = redisTemplate.opsForList().rightPushAll(key, values); return count == null ? 0 : count; } /** * 从List中获取begin到end之间的元素 * * @param key Redis键 * @param start 开始位置 * @param end 结束位置(start=0,end=-1表示获取全部元素) * @return List对象 */ public List<Object> listGet(final String key, final int start, final int end) { return redisTemplate.opsForList().range(key, start, end); } }
5:测试
@SpringBootTest
class RedisJavaApplicationTests {
@Autowired
private RedisUtils redisUtils;
@Test
void contextLoads(){
//直接保存
redisUtils.set("token", list);
//保存到Redis并且设置过期时间
redisUtils.set("司", "夏", 30, TimeUnit.SECONDS);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。