diff --git a/demo-cache/demo-cache-api/pom.xml b/demo-cache/demo-cache-api/pom.xml new file mode 100644 index 0000000..e81d987 --- /dev/null +++ b/demo-cache/demo-cache-api/pom.xml @@ -0,0 +1,36 @@ + + + + com.xkcoding + demo-cache + 1.0.0-SNAPSHOT + + + 4.0.0 + + demo-cache-api + + + 17 + + + + + org.springframework.boot + spring-boot-starter + + + + org.projectlombok + lombok + true + + + + + demo-cache-api + + + diff --git a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/service/impl/UserServiceImpl.java b/demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/api/UserService.java similarity index 66% rename from demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/service/impl/UserServiceImpl.java rename to demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/api/UserService.java index f7b7d1f..aa07601 100644 --- a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/service/impl/UserServiceImpl.java +++ b/demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/api/UserService.java @@ -1,40 +1,34 @@ -package com.xkcoding.cache.redis.service.impl; +package com.xkcoding.cache.api; -import com.google.common.collect.Maps; -import com.xkcoding.cache.redis.entity.User; -import com.xkcoding.cache.redis.service.UserService; +import com.xkcoding.cache.entity.User; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; +import java.util.HashMap; import java.util.Map; /** *

- * UserService + * 模拟用户服务 *

* * @author yangkai.shen - * @date Created in 2018-11-15 16:45 + * @date Created in 2022-09-07 14:08 */ -@Service @Slf4j -public class UserServiceImpl implements UserService { +@Service +public class UserService { /** * 模拟数据库 */ - private static final Map DATABASES = Maps.newConcurrentMap(); - - /** - * 初始化数据 - */ - static { - DATABASES.put(1L, new User(1L, "user1")); - DATABASES.put(2L, new User(2L, "user2")); - DATABASES.put(3L, new User(3L, "user3")); - } + private static final Map DATABASES = new HashMap<>() {{ + put(1L, new User(1L, "user1")); + put(2L, new User(2L, "user2")); + put(3L, new User(3L, "user3")); + }}; /** * 保存或修改用户 @@ -43,7 +37,6 @@ public class UserServiceImpl implements UserService { * @return 操作结果 */ @CachePut(value = "user", key = "#user.id") - @Override public User saveOrUpdate(User user) { DATABASES.put(user.getId(), user); log.info("保存用户【user】= {}", user); @@ -57,7 +50,6 @@ public class UserServiceImpl implements UserService { * @return 返回结果 */ @Cacheable(value = "user", key = "#id") - @Override public User get(Long id) { // 我们假设从数据库读取 log.info("查询用户【id】= {}", id); @@ -70,7 +62,6 @@ public class UserServiceImpl implements UserService { * @param id key值 */ @CacheEvict(value = "user", key = "#id") - @Override public void delete(Long id) { DATABASES.remove(id); log.info("删除用户【id】= {}", id); diff --git a/demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/autoconfigure/CacheMockServiceAutoConfiguration.java b/demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/autoconfigure/CacheMockServiceAutoConfiguration.java new file mode 100644 index 0000000..c93e198 --- /dev/null +++ b/demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/autoconfigure/CacheMockServiceAutoConfiguration.java @@ -0,0 +1,21 @@ +package com.xkcoding.cache.autoconfigure; + +import com.xkcoding.cache.api.UserService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + *

+ * 缓存 mock 自动装配 + *

+ * + * @author yangkai.shen + * @date 2022-09-07 14:31 + */ +@Configuration(proxyBeanMethods = false) +public class CacheMockServiceAutoConfiguration { + @Bean + public UserService userService() { + return new UserService(); + } +} diff --git a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/entity/User.java b/demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/entity/User.java similarity index 78% rename from demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/entity/User.java rename to demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/entity/User.java index f3128e8..90889f1 100644 --- a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/entity/User.java +++ b/demo-cache/demo-cache-api/src/main/java/com/xkcoding/cache/entity/User.java @@ -1,23 +1,25 @@ -package com.xkcoding.cache.redis.entity; +package com.xkcoding.cache.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.io.Serial; import java.io.Serializable; /** *

- * 用户实体 + * 用户对象 *

* * @author yangkai.shen - * @date Created in 2018-11-15 16:39 + * @date Created in 2022-09-07 13:54 */ @Data @AllArgsConstructor @NoArgsConstructor public class User implements Serializable { + @Serial private static final long serialVersionUID = 2892248514883451461L; /** * 主键id diff --git a/demo-cache/demo-cache-api/src/main/resources/META-INF/spring.factories b/demo-cache/demo-cache-api/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000..8977fb0 --- /dev/null +++ b/demo-cache/demo-cache-api/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.xkcoding.cache.autoconfigure.CacheMockServiceAutoConfiguration diff --git a/demo-cache/demo-cache-redis/.gitignore b/demo-cache/demo-cache-redis/.gitignore deleted file mode 100644 index 82eca33..0000000 --- a/demo-cache/demo-cache-redis/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/build/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ \ No newline at end of file diff --git a/demo-cache/demo-cache-redis/README.md b/demo-cache/demo-cache-redis/README.md index 7baebf5..92e9585 100644 --- a/demo-cache/demo-cache-redis/README.md +++ b/demo-cache/demo-cache-redis/README.md @@ -1,94 +1,56 @@ -# spring-boot-demo-cache-redis +## spring-boot-demo-cache-redis > 此 demo 主要演示了 Spring Boot 如何整合 redis,操作redis中的数据,并使用redis缓存数据。连接池使用 Lettuce。 -## pom.xml +### 1.开发步骤 -```xml - - - 4.0.0 +#### 1.1.添加依赖 - spring-boot-demo-cache-redis +```xml + + + com.xkcoding + common-tools + + + + com.xkcoding + demo-cache-api 1.0.0-SNAPSHOT - jar - - spring-boot-demo-cache-redis - Demo project for Spring Boot - - - com.xkcoding - spring-boot-demo - 1.0.0-SNAPSHOT - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - - org.apache.commons - commons-pool2 - - - - - org.springframework.boot - spring-boot-starter-json - - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.google.guava - guava - - - - cn.hutool - hutool-all - - - - org.projectlombok - lombok - true - - - - - spring-boot-demo-cache-redis - - - org.springframework.boot - spring-boot-maven-plugin - - - - - + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + + org.apache.commons + commons-pool2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.projectlombok + lombok + true + + ``` -## application.yml +#### 1.2.配置文件 ```yaml spring: @@ -116,21 +78,13 @@ logging: com.xkcoding: debug ``` -## RedisConfig.java +#### 1.3.自动装配Redis缓存管理 ```java -/** - *

- * redis配置 - *

- * - * @author yangkai.shen - * @date Created in 2018-11-15 16:41 - */ +@EnableCaching @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) -@EnableCaching -public class RedisConfig { +public class RedisCacheAutoConfiguration { /** * 默认情况下的模板只能支持RedisTemplate,也就是只能存入字符串,因此支持序列化 @@ -151,40 +105,31 @@ public class RedisConfig { public CacheManager cacheManager(RedisConnectionFactory factory) { // 配置序列化 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); - RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); + RedisCacheConfiguration redisCacheConfiguration = + config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build(); } } ``` -## UserServiceImpl.java +#### 1.4.缓存通过注解实现 + +> 为了减少重复代码,该部分我将其抽取实现在 demo-cache-api 模块中 ```java -/** - *

- * UserService - *

- * - * @author yangkai.shen - * @date Created in 2018-11-15 16:45 - */ -@Service @Slf4j -public class UserServiceImpl implements UserService { +@Service +public class UserService { /** * 模拟数据库 */ - private static final Map DATABASES = Maps.newConcurrentMap(); - - /** - * 初始化数据 - */ - static { - DATABASES.put(1L, new User(1L, "user1")); - DATABASES.put(2L, new User(2L, "user2")); - DATABASES.put(3L, new User(3L, "user3")); - } + private static final Map DATABASES = new HashMap<>() {{ + put(1L, new User(1L, "user1")); + put(2L, new User(2L, "user2")); + put(3L, new User(3L, "user3")); + }}; /** * 保存或修改用户 @@ -193,7 +138,6 @@ public class UserServiceImpl implements UserService { * @return 操作结果 */ @CachePut(value = "user", key = "#user.id") - @Override public User saveOrUpdate(User user) { DATABASES.put(user.getId(), user); log.info("保存用户【user】= {}", user); @@ -207,7 +151,6 @@ public class UserServiceImpl implements UserService { * @return 返回结果 */ @Cacheable(value = "user", key = "#id") - @Override public User get(Long id) { // 我们假设从数据库读取 log.info("查询用户【id】= {}", id); @@ -220,7 +163,6 @@ public class UserServiceImpl implements UserService { * @param id key值 */ @CacheEvict(value = "user", key = "#id") - @Override public void delete(Long id) { DATABASES.remove(id); log.info("删除用户【id】= {}", id); @@ -228,9 +170,20 @@ public class UserServiceImpl implements UserService { } ``` -## RedisTest.java +### 2.测试 + +#### 2.1.环境搭建 -> 主要测试使用 `RedisTemplate` 操作 `Redis` 中的数据: +主要是 redis 环境的搭建,这里我提供了 docker-compose 文件,方便同学们一键启动测试环境 + +```bash +$ cd demo-cache/demo-cache-redis +$ docker compose -f docker-compose.env.yml up +``` + +#### 2.2.测试 Redis 基础功能 + +> 主要测试使用 `RedisTemplate` 操作 `Redis` 中的数据,查看是否正常序列化: > > - opsForValue:对应 String(字符串) > - opsForZSet:对应 ZSet(有序集合) @@ -240,16 +193,9 @@ public class UserServiceImpl implements UserService { > - opsForGeo:** 对应 GEO(地理位置) ```java -/** - *

- * Redis测试 - *

- * - * @author yangkai.shen - * @date Created in 2018-11-15 17:17 - */ @Slf4j -public class RedisTest extends SpringBootDemoCacheRedisApplicationTests { +@SpringBootTest +public class RedisTest { @Autowired private StringRedisTemplate stringRedisTemplate; @@ -261,13 +207,19 @@ public class RedisTest extends SpringBootDemoCacheRedisApplicationTests { * 测试 Redis 操作 */ @Test - public void get() { + public void get() throws InterruptedException { // 测试线程安全,程序结束查看redis中count的值是否为1000 ExecutorService executorService = Executors.newFixedThreadPool(1000); - IntStream.range(0, 1000).forEach(i -> executorService.execute(() -> stringRedisTemplate.opsForValue().increment("count", 1))); + CountDownLatch wait = new CountDownLatch(1000); + IntStream.range(0, 1000).forEach(i -> executorService.execute(() -> { + stringRedisTemplate.opsForValue().increment("count", 1); + wait.countDown(); + })); + wait.await(); + log.debug("【count】= {}", stringRedisTemplate.opsForValue().getAndExpire("count", Duration.ofSeconds(10))); stringRedisTemplate.opsForValue().set("k1", "v1"); - String k1 = stringRedisTemplate.opsForValue().get("k1"); + String k1 = stringRedisTemplate.opsForValue().getAndExpire("k1", Duration.ofSeconds(10)); log.debug("【k1】= {}", k1); // 以下演示整合,具体Redis命令可以参考官方文档 @@ -275,27 +227,19 @@ public class RedisTest extends SpringBootDemoCacheRedisApplicationTests { redisCacheTemplate.opsForValue().set(key, new User(1L, "user1")); // 对应 String(字符串) User user = (User) redisCacheTemplate.opsForValue().get(key); + String userSerialized = stringRedisTemplate.opsForValue().getAndExpire(key, Duration.ofSeconds(10)); log.debug("【user】= {}", user); + log.debug("【userSerialized】= {}", userSerialized); } } - ``` -## UserServiceTest.java - -> 主要测试使用Redis缓存是否起效 +#### 2.3.测试Redis缓存是否生效 ```java -/** - *

- * Redis - 缓存测试 - *

- * - * @author yangkai.shen - * @date Created in 2018-11-15 16:53 - */ @Slf4j -public class UserServiceTest extends SpringBootDemoCacheRedisApplicationTests { +@SpringBootTest +public class UserServiceTest { @Autowired private UserService userService; @@ -340,8 +284,9 @@ public class UserServiceTest extends SpringBootDemoCacheRedisApplicationTests { } ``` -## 参考 +### 3.参考 -- spring-data-redis 官方文档:https://docs.spring.io/spring-data/redis/docs/2.0.1.RELEASE/reference/html/ -- redis 文档:https://redis.io/documentation -- redis 中文文档:http://www.redis.cn/commands.html +- [Spring Boot 官方文档之连接 Redis](https://docs.spring.io/spring-boot/docs/3.0.0-M4/reference/htmlsingle/#data.nosql.redis) +- [Spring Boot 官方文档之 Redis 缓存](https://docs.spring.io/spring-boot/docs/3.0.0-M4/reference/htmlsingle/#io.caching.provider.redis) +- [spring-data-redis 官方文档](https://docs.spring.io/spring-data/redis/docs/3.0.0-M5/reference/html/) +- [Redis 官方文档](https://redis.io/docs/) diff --git a/demo-cache/demo-cache-redis/docker-compose.env.yml b/demo-cache/demo-cache-redis/docker-compose.env.yml new file mode 100644 index 0000000..5ca5b09 --- /dev/null +++ b/demo-cache/demo-cache-redis/docker-compose.env.yml @@ -0,0 +1,7 @@ +version: "3.8" + +services: + redis: + image: redis:7.0.4-alpine + ports: + - "6379:6379" diff --git a/demo-cache/demo-cache-redis/pom.xml b/demo-cache/demo-cache-redis/pom.xml index 5f11beb..f5391cb 100644 --- a/demo-cache/demo-cache-redis/pom.xml +++ b/demo-cache/demo-cache-redis/pom.xml @@ -1,81 +1,75 @@ - 4.0.0 - - demo-cache-redis + + com.xkcoding + demo-cache 1.0.0-SNAPSHOT - jar + - demo-cache-redis - Demo project for Spring Boot + 4.0.0 - - com.xkcoding - spring-boot-demo - 1.0.0-SNAPSHOT - + demo-cache-redis + 1.0.0-SNAPSHOT + jar - - UTF-8 - UTF-8 - 1.8 - + demo-cache-redis + Demo project for Spring Boot - - - org.springframework.boot - spring-boot-starter - + + 17 + - - org.springframework.boot - spring-boot-starter-data-redis - + + + com.xkcoding + common-tools + - - - org.apache.commons - commons-pool2 - + + com.xkcoding + demo-cache-api + 1.0.0-SNAPSHOT + - - - org.springframework.boot - spring-boot-starter-json - + + org.springframework.boot + spring-boot-starter-web + - - org.springframework.boot - spring-boot-starter-test - test - + + org.springframework.boot + spring-boot-starter-data-redis + - - com.google.guava - guava - + + + + org.apache.commons + commons-pool2 + - - cn.hutool - hutool-all - + + org.springframework.boot + spring-boot-starter-test + test + - - org.projectlombok - lombok - true - - + + org.projectlombok + lombok + true + + - - demo-cache-redis - - - org.springframework.boot - spring-boot-maven-plugin - - - + + demo-cache-redis + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/SpringBootDemoCacheRedisApplication.java b/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/RedisCacheApplication.java similarity index 53% rename from demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/SpringBootDemoCacheRedisApplication.java rename to demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/RedisCacheApplication.java index ad52a4c..5e5ec77 100644 --- a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/SpringBootDemoCacheRedisApplication.java +++ b/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/RedisCacheApplication.java @@ -3,10 +3,18 @@ package com.xkcoding.cache.redis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +/** + *

+ * 启动器 + *

+ * + * @author yangkai.shen + * @date Created in 2022-09-06 23:09 + */ @SpringBootApplication -public class SpringBootDemoCacheRedisApplication { +public class RedisCacheApplication { public static void main(String[] args) { - SpringApplication.run(SpringBootDemoCacheRedisApplication.class, args); + SpringApplication.run(RedisCacheApplication.class, args); } } diff --git a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/config/RedisConfig.java b/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/configuration/RedisCacheAutoConfiguration.java similarity index 80% rename from demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/config/RedisConfig.java rename to demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/configuration/RedisCacheAutoConfiguration.java index dae7aed..ee1c5b7 100644 --- a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/config/RedisConfig.java +++ b/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/configuration/RedisCacheAutoConfiguration.java @@ -1,4 +1,4 @@ -package com.xkcoding.cache.redis.config; +package com.xkcoding.cache.redis.configuration; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; @@ -19,16 +19,16 @@ import java.io.Serializable; /** *

- * redis配置 + * redis 缓存自动装配,同时设置 redis 序列化 *

* * @author yangkai.shen - * @date Created in 2018-11-15 16:41 + * @date Created in 2022-09-07 14:03 */ +@EnableCaching @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) -@EnableCaching -public class RedisConfig { +public class RedisCacheAutoConfiguration { /** * 默认情况下的模板只能支持RedisTemplate,也就是只能存入字符串,因此支持序列化 @@ -49,7 +49,9 @@ public class RedisConfig { public CacheManager cacheManager(RedisConnectionFactory factory) { // 配置序列化 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); - RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); + RedisCacheConfiguration redisCacheConfiguration = + config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build(); } diff --git a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/service/UserService.java b/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/service/UserService.java deleted file mode 100644 index 331901b..0000000 --- a/demo-cache/demo-cache-redis/src/main/java/com/xkcoding/cache/redis/service/UserService.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.xkcoding.cache.redis.service; - -import com.xkcoding.cache.redis.entity.User; - -/** - *

- * UserService - *

- * - * @author yangkai.shen - * @date Created in 2018-11-15 16:45 - */ -public interface UserService { - /** - * 保存或修改用户 - * - * @param user 用户对象 - * @return 操作结果 - */ - User saveOrUpdate(User user); - - /** - * 获取用户 - * - * @param id key值 - * @return 返回结果 - */ - User get(Long id); - - /** - * 删除 - * - * @param id key值 - */ - void delete(Long id); -} diff --git a/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/RedisCacheApplicationTests.java b/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/RedisCacheApplicationTests.java new file mode 100644 index 0000000..0f8cc07 --- /dev/null +++ b/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/RedisCacheApplicationTests.java @@ -0,0 +1,13 @@ +package com.xkcoding.cache.redis; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RedisCacheApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/RedisTest.java b/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/RedisTest.java index 8389ea5..ac5c74a 100644 --- a/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/RedisTest.java +++ b/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/RedisTest.java @@ -1,27 +1,31 @@ package com.xkcoding.cache.redis; -import com.xkcoding.cache.redis.entity.User; +import com.xkcoding.cache.entity.User; import lombok.extern.slf4j.Slf4j; -import org.junit.Test; +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 org.springframework.data.redis.core.StringRedisTemplate; import java.io.Serializable; +import java.time.Duration; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.IntStream; /** *

- * Redis测试 + * redis 基础用法 *

* * @author yangkai.shen - * @date Created in 2018-11-15 17:17 + * @date Created in 2022-09-07 13:48 */ @Slf4j -public class RedisTest extends SpringBootDemoCacheRedisApplicationTests { +@SpringBootTest +public class RedisTest { @Autowired private StringRedisTemplate stringRedisTemplate; @@ -33,13 +37,19 @@ public class RedisTest extends SpringBootDemoCacheRedisApplicationTests { * 测试 Redis 操作 */ @Test - public void get() { + public void get() throws InterruptedException { // 测试线程安全,程序结束查看redis中count的值是否为1000 ExecutorService executorService = Executors.newFixedThreadPool(1000); - IntStream.range(0, 1000).forEach(i -> executorService.execute(() -> stringRedisTemplate.opsForValue().increment("count", 1))); + CountDownLatch wait = new CountDownLatch(1000); + IntStream.range(0, 1000).forEach(i -> executorService.execute(() -> { + stringRedisTemplate.opsForValue().increment("count", 1); + wait.countDown(); + })); + wait.await(); + log.debug("【count】= {}", stringRedisTemplate.opsForValue().getAndExpire("count", Duration.ofSeconds(10))); stringRedisTemplate.opsForValue().set("k1", "v1"); - String k1 = stringRedisTemplate.opsForValue().get("k1"); + String k1 = stringRedisTemplate.opsForValue().getAndExpire("k1", Duration.ofSeconds(10)); log.debug("【k1】= {}", k1); // 以下演示整合,具体Redis命令可以参考官方文档 @@ -47,6 +57,8 @@ public class RedisTest extends SpringBootDemoCacheRedisApplicationTests { redisCacheTemplate.opsForValue().set(key, new User(1L, "user1")); // 对应 String(字符串) User user = (User) redisCacheTemplate.opsForValue().get(key); + String userSerialized = stringRedisTemplate.opsForValue().getAndExpire(key, Duration.ofSeconds(10)); log.debug("【user】= {}", user); + log.debug("【userSerialized】= {}", userSerialized); } } diff --git a/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/SpringBootDemoCacheRedisApplicationTests.java b/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/SpringBootDemoCacheRedisApplicationTests.java deleted file mode 100644 index b70f59a..0000000 --- a/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/SpringBootDemoCacheRedisApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xkcoding.cache.redis; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringBootDemoCacheRedisApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/service/UserServiceTest.java b/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/service/UserServiceTest.java index 3318787..8ba76be 100644 --- a/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/service/UserServiceTest.java +++ b/demo-cache/demo-cache-redis/src/test/java/com/xkcoding/cache/redis/service/UserServiceTest.java @@ -1,10 +1,11 @@ package com.xkcoding.cache.redis.service; -import com.xkcoding.cache.redis.SpringBootDemoCacheRedisApplicationTests; -import com.xkcoding.cache.redis.entity.User; +import com.xkcoding.cache.api.UserService; +import com.xkcoding.cache.entity.User; import lombok.extern.slf4j.Slf4j; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; /** *

@@ -12,10 +13,11 @@ import org.springframework.beans.factory.annotation.Autowired; *

* * @author yangkai.shen - * @date Created in 2018-11-15 16:53 + * @date Created in 2022-09-07 14:37 */ @Slf4j -public class UserServiceTest extends SpringBootDemoCacheRedisApplicationTests { +@SpringBootTest +public class UserServiceTest { @Autowired private UserService userService; diff --git a/demo-cache/pom.xml b/demo-cache/pom.xml index 8100d25..89df467 100644 --- a/demo-cache/pom.xml +++ b/demo-cache/pom.xml @@ -18,4 +18,9 @@ 17 + + demo-cache-api + demo-cache-redis + +