网站建设团队架构,在家开网店怎么开,网络营销失败案例及分析,建设工程合同包括三种【Spring Boot 3】【Redis】基本数据类型操作 背景介绍开发环境开发步骤及源码工程目录结构 背景
软件开发是一门实践性科学#xff0c;对大多数人来说#xff0c;学习一种新技术不是一开始就去深究其原理#xff0c;而是先从做出一个可工作的DEMO入手。但在我个人学习和工… 【Spring Boot 3】【Redis】基本数据类型操作 背景介绍开发环境开发步骤及源码工程目录结构 背景
软件开发是一门实践性科学对大多数人来说学习一种新技术不是一开始就去深究其原理而是先从做出一个可工作的DEMO入手。但在我个人学习和工作经历中每次学习新技术总是要花费或多或少的时间、检索不止一篇资料才能得出一个可工作的DEMO这占用了我大量的时间精力。因此本文旨在通过一篇文章即能还原出可工作的、甚至可用于生产的DEMO期望初学者能尽快地迈过0到1的这一步骤并在此基础上不断深化对相关知识的理解。 为达以上目的本文会将开发环境、工程目录结构、开发步骤及源码尽量全面地展现出来文字描述能简则简能用代码注释的绝不在正文中再啰嗦一遍正文仅对必要且关键的信息做重点描述。
介绍
本文介绍开发Spring Boot应用时借助Spring Data Redis实现对Redis五种基本数据字符串string、哈希hash、列表list、集合set、有序集合zset类型的操作。
开发环境
分类名称版本操作系统WindowsWindows 11JDKOracle JDK21.0.1IDEIntelliJ IDEA2023.2.4构建工具Apache Maven3.9.3缓存Redis7.2
开发步骤及源码
1 创建Maven工程添加依赖。 propertiesspring-boot.version3.2.1/spring-boot.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactIdversion${spring-boot.version}/version/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdversion${spring-boot.version}/versionscopetest/scope/dependencydependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactIdversion2.15.3/version/dependency/dependencies2 添加应用配置src/main/resources/application.yml。
spring:data:redis:# 连接地址host: 127.0.0.1# 端口port: 6379# Redis数据库索引默认为 0database: 0# 用户名可选# username:# 密码可选# password:3 定义SpringBoot应用启动类。
package com.jiyongliang.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;SpringBootApplication
public class SpringBoot3RedisDataApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot3RedisDataApplication.class, args);}
}4 字符串string
package com.jiyongliang.springboot;import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
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;SpringBootTest
class RedisStringTests {AutowiredRedisTemplateString, Object redisTemplate;String key string-key;AfterEachvoid afterEach() {redisTemplate.delete(key);}Testvoid testString() {// 添加字符串缓存数据redisTemplate.opsForValue().set(key, string data);// 获取字符串缓存数据String cachedString (String) redisTemplate.opsForValue().get(key);Assertions.assertThat(cachedString).isNotNull().isEqualTo(string data);}
}5 哈希hash
package com.jiyongliang.springboot;import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
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.HashMap;
import java.util.Map;SpringBootTest
class RedisHashTests {AutowiredRedisTemplateString, Object redisTemplate;String key hash-single-key;BeforeEachvoid beforeEach() {redisTemplate.delete(key);}Testvoid testHash() {// 添加单个Hash缓存数据redisTemplate.opsForHash().put(key, hash key, hash value);// 获取单个Hash缓存数据String cachedHash (String) redisTemplate.opsForHash().get(key, hash key);Assertions.assertThat(cachedHash).isEqualTo(hash value);redisTemplate.delete(key);// 添加map缓存数据MapString, String map new HashMap();map.put(map-key-1, map value 1);map.put(map-key-2, map value 2);map.put(map-key-3, map value 3);redisTemplate.opsForHash().putAll(key, map);// 获取map缓存数据MapObject, Object cachedHashMap redisTemplate.opsForHash().entries(key);Assertions.assertThat(cachedHashMap).isNotNull().containsEntry(map-key-1, map value 1).containsEntry(map-key-2, map value 2).containsEntry(map-key-3, map value 3);}
}6 列表list
package com.jiyongliang.springboot;import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
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.List;SpringBootTest
class RedisListTests {AutowiredRedisTemplateString, Object redisTemplate;String key list-key;BeforeEachvoid beforeEach() {redisTemplate.delete(key);}Testvoid testList() {// 添加List缓存数据redisTemplate.opsForList().leftPush(key, list value 3);redisTemplate.opsForList().leftPush(key, list value 2);redisTemplate.opsForList().leftPush(key, list value 1);redisTemplate.opsForList().rightPush(key, list value 4);redisTemplate.opsForList().rightPush(key, list value 5);// 获取全部List缓存数据ListObject cachedList redisTemplate.opsForList().range(key, 0, -1);Assertions.assertThat(cachedList).isNotNull().isNotEmpty().hasToString([list value 1, list value 2, list value 3, list value 4, list value 5]);// 获取指定下标数据String listValue (String) redisTemplate.opsForList().index(key, 2);Assertions.assertThat(listValue).isEqualTo(list value 3);listValue (String) redisTemplate.opsForList().index(key, 5);Assertions.assertThat(listValue).isNull();// 从左边开始取数据listValue (String) redisTemplate.opsForList().leftPop(key);Assertions.assertThat(listValue).isEqualTo(list value 1);// 从右边开始取数据listValue (String) redisTemplate.opsForList().rightPop(key);Assertions.assertThat(listValue).isEqualTo(list value 5);// 获取list长度Long length redisTemplate.opsForList().size(key);Assertions.assertThat(length).isNotNull().isEqualTo(3);Assertions.assertThat(redisTemplate.opsForList().range(key, 0, -1)).isNotNull().isNotEmpty().hasToString([list value 2, list value 3, list value 4]);}
}7 集合set
package com.jiyongliang.springboot;import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
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.Arrays;
import java.util.Set;
import java.util.stream.Collectors;SpringBootTest
class RedisSetTests {AutowiredRedisTemplateString, Object redisTemplate;String key1 set-key-1;String key2 set-key-2;BeforeEachvoid beforeEach() {redisTemplate.delete(key1);redisTemplate.delete(key2);}Testvoid testSet() {// 添加Set缓存数据String[] setData new String[]{A, B, C, D, D, C, D, E, F, F, G};Long addCount redisTemplate.opsForSet().add(key1, setData);SetString expected Arrays.stream(setData).collect(Collectors.toSet());Assertions.assertThat(addCount).isNotNull().isEqualTo(expected.size());// 获取Set缓存数据SetObject cachedSet redisTemplate.opsForSet().members(key1);Assertions.assertThat(cachedSet).isNotNull().hasSameSizeAs(expected).containsAll(expected);// 判断是否在Set缓存数据中Assertions.assertThat(redisTemplate.opsForSet().isMember(key1, F)).isTrue();Assertions.assertThat(redisTemplate.opsForSet().isMember(key1, X)).isFalse();// 返回缓存Set的并集String[] setTempData new String[]{A, X, E, Y, G, Z};redisTemplate.opsForSet().add(key2, setTempData);SetObject unionSet redisTemplate.opsForSet().union(key1, key2);Assertions.assertThat(unionSet).isNotNull().hasSize(expected.size() 3).containsAll(expected).containsAll(Set.of(X, Y, Z));// 返回缓存Set的交集SetObject intersectSet redisTemplate.opsForSet().intersect(key1, key2);Assertions.assertThat(intersectSet).isNotNull().hasSize(3).containsAll(Set.of(A, E, G));// 返回缓存的set-key-1中存在但set-key-2中不存在的数据SetObject differenceSet redisTemplate.opsForSet().difference(key1, key2);Assertions.assertThat(differenceSet).isNotNull().hasSize(expected.size() - 3).containsAll(Set.of(B, C, D, F));}
}8 有序集合zset
package com.jiyongliang.springboot;import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
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.Set;SpringBootTest
class RedisZSetTests {AutowiredRedisTemplateString, Object redisTemplate;String key zset-key;BeforeEachvoid beforeEach() {redisTemplate.delete(key);}Testvoid testZSet() {// 添加ZSet缓存数据redisTemplate.opsForZSet().add(key, X, 1);redisTemplate.opsForZSet().add(key, Y, 2);redisTemplate.opsForZSet().add(key, Z, 3);// 值相同的情况下权重会被覆盖redisTemplate.opsForZSet().add(key, X, 1);redisTemplate.opsForZSet().add(key, Y, 3);redisTemplate.opsForZSet().add(key, Z, 5);// 获取ZSet缓存数据SetObject cachedZSet redisTemplate.opsForZSet().range(key, 0, -1);Assertions.assertThat(cachedZSet).isNotNull().hasSize(3).containsAll(Set.of(X, Y, Z));// 获取值对应的权重Double score redisTemplate.opsForZSet().score(key, Y);Assertions.assertThat(score).isNotNull().isEqualTo(3);// 获取值对应的排名从0开始Long rank redisTemplate.opsForZSet().rank(key, Y);Assertions.assertThat(rank).isNotNull().isEqualTo(1);// 根据score范围获取值SetObject rangedZSet redisTemplate.opsForZSet().rangeByScore(key, 1, 4);Assertions.assertThat(rangedZSet).isNotNull().hasSize(2).containsAll(Set.of(X, Y));}
}9 数据过期
package com.jiyongliang.springboot;import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
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 RedisExpireTests {AutowiredRedisTemplateString, Object redisTemplate;String key expire-key;BeforeEachvoid beforeEach() {redisTemplate.delete(key);}Testvoid testExpire() throws InterruptedException {redisTemplate.opsForValue().set(key, expire data);Assertions.assertThat(redisTemplate.opsForValue().get(key)).isNotNull().isEqualTo(expire data);redisTemplate.opsForValue().getOperations().expire(key, 3, TimeUnit.SECONDS);TimeUnit.SECONDS.sleep(3);Assertions.assertThat(redisTemplate.opsForValue().get(key)).isNull();}
}10 单元测试结果
工程目录结构