From b8b47bf59527c386d13a193ad5937fa810c12fe1 Mon Sep 17 00:00:00 2001 From: Administrator Date: Tue, 3 Nov 2020 16:02:24 +0800 Subject: [PATCH] =?UTF-8?q?1.=20=E4=BF=AE=E6=AD=A3=E4=BA=86=20redis-starte?= =?UTF-8?q?r=20=E4=B8=AD=20cache=20=E5=8F=8D=E5=BA=8F=E5=88=97=E5=8C=96?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98=202.=20=E5=A2=9E=E5=8A=A0=E4=BA=86?= =?UTF-8?q?=20redis-cache=20=E5=AE=9E=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/redis-cache-example/pom.xml | 31 ++++ .../example/RedisCacheExampleApplication.java | 13 ++ .../cloud/redis/cache/example/model/User.java | 19 +++ .../cache/example/service/ExampleService.java | 22 +++ .../service/impl/ExampleServiceImpl.java | 55 +++++++ .../src/main/resources/application-redis.yml | 16 +++ .../src/main/resources/application.yml | 10 ++ .../cache/example/RedisCacheExampleTest.java | 41 ++++++ .../src/main/resources/application-redis.yml | 4 - .../starter/config/JsonRedisSerializer.java | 136 +++++++++--------- .../config/cache/RedisCacheConfiguration.java | 8 +- 11 files changed, 279 insertions(+), 76 deletions(-) create mode 100644 examples/redis-cache-example/pom.xml create mode 100644 examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/RedisCacheExampleApplication.java create mode 100644 examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/model/User.java create mode 100644 examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/service/ExampleService.java create mode 100644 examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/service/impl/ExampleServiceImpl.java create mode 100644 examples/redis-cache-example/src/main/resources/application-redis.yml create mode 100644 examples/redis-cache-example/src/main/resources/application.yml create mode 100644 examples/redis-cache-example/src/test/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/RedisCacheExampleTest.java diff --git a/examples/redis-cache-example/pom.xml b/examples/redis-cache-example/pom.xml new file mode 100644 index 0000000..976ffb2 --- /dev/null +++ b/examples/redis-cache-example/pom.xml @@ -0,0 +1,31 @@ + + 4.0.0 + + com.chinaunicom.ebtp + mall-ebtp-cloud-parent + 0.0.1 + + com.chinaunicom.mall.ebtp.cloud + redis-cache-example + 0.0.1-SNAPSHOT + jar + + redis-cache-example + + + com.chinaunicom.ebtp + mall-ebtp-cloud-redis-starter + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/RedisCacheExampleApplication.java b/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/RedisCacheExampleApplication.java new file mode 100644 index 0000000..1eea419 --- /dev/null +++ b/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/RedisCacheExampleApplication.java @@ -0,0 +1,13 @@ +package com.chinaunicom.mall.ebtp.cloud.redis.cache.example; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +@SpringBootApplication +@EnableCaching +public class RedisCacheExampleApplication { + public static void main(String[] args) { + SpringApplication.run(RedisCacheExampleApplication.class, args); + } +} diff --git a/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/model/User.java b/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/model/User.java new file mode 100644 index 0000000..b4ed0b7 --- /dev/null +++ b/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/model/User.java @@ -0,0 +1,19 @@ +package com.chinaunicom.mall.ebtp.cloud.redis.cache.example.model; + +import java.io.Serializable; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class User implements Serializable { + private static final long serialVersionUID = 1L; + + private Integer id; + private String username; + private Integer age; + +} diff --git a/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/service/ExampleService.java b/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/service/ExampleService.java new file mode 100644 index 0000000..e079aad --- /dev/null +++ b/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/service/ExampleService.java @@ -0,0 +1,22 @@ +package com.chinaunicom.mall.ebtp.cloud.redis.cache.example.service; + +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; + +import com.chinaunicom.mall.ebtp.cloud.redis.cache.example.model.User; + +@CacheConfig(cacheNames = "user") +public interface ExampleService { + + @CachePut(key = "#user.id") + User update(User user); + + @CacheEvict(key = "#id", allEntries = true) + void deleteById(Integer id); + + @Cacheable(key = "#id") + User queryById(Integer id); + +} diff --git a/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/service/impl/ExampleServiceImpl.java b/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/service/impl/ExampleServiceImpl.java new file mode 100644 index 0000000..7b779d5 --- /dev/null +++ b/examples/redis-cache-example/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/service/impl/ExampleServiceImpl.java @@ -0,0 +1,55 @@ +package com.chinaunicom.mall.ebtp.cloud.redis.cache.example.service.impl; + +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; + +import com.chinaunicom.mall.ebtp.cloud.redis.cache.example.model.User; +import com.chinaunicom.mall.ebtp.cloud.redis.cache.example.service.ExampleService; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +public class ExampleServiceImpl implements ExampleService { + private ConcurrentHashMap userRepo = new ConcurrentHashMap<>(); + + ExampleServiceImpl() { + log.info("Example database initial"); + + for (int i = 1; i <= 10; i++) { + userRepo.put(i, new User(i, "test" + i, i + 20)); + } + } + + @Override + public User update(User user) { + log.info(String.format("Find user by id [%s]", user.getId())); + User target = userRepo.get(user.getId()); + if (!Objects.isNull(target)) { + BeanUtils.copyProperties(user, target); + } + return target; + } + + @Override + public void deleteById(Integer id) { + log.info(String.format("Delete user by id [%s]", id)); + userRepo.remove(id); + } + + @Override + public User queryById(Integer id) { + log.info(String.format("Query user by id [%s]", id)); +// List list = new ArrayList(); +// +// for(int i = 1; i < id; i++) { +// list.add(userRepo.get(i)); +// } +// return list; + return userRepo.get(id); + } + +} diff --git a/examples/redis-cache-example/src/main/resources/application-redis.yml b/examples/redis-cache-example/src/main/resources/application-redis.yml new file mode 100644 index 0000000..eda917b --- /dev/null +++ b/examples/redis-cache-example/src/main/resources/application-redis.yml @@ -0,0 +1,16 @@ +spring: + redis: + database: 0 + host: 125.32.114.204 + password: redis@CC1234 + port: 16379 + timeout: 6000 + ssl: false + lettuce: + pool: + max-wait: -1ms + max-active: 8 + max-idle: 8 + min-idle: 0 + cache: + cacheNames: demo \ No newline at end of file diff --git a/examples/redis-cache-example/src/main/resources/application.yml b/examples/redis-cache-example/src/main/resources/application.yml new file mode 100644 index 0000000..71e65d1 --- /dev/null +++ b/examples/redis-cache-example/src/main/resources/application.yml @@ -0,0 +1,10 @@ +spring: + profiles: + active: redis + application: + name: mall-ebtp-cloud-demo + +logging: + level: + root: info + \ No newline at end of file diff --git a/examples/redis-cache-example/src/test/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/RedisCacheExampleTest.java b/examples/redis-cache-example/src/test/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/RedisCacheExampleTest.java new file mode 100644 index 0000000..865082c --- /dev/null +++ b/examples/redis-cache-example/src/test/java/com/chinaunicom/mall/ebtp/cloud/redis/cache/example/RedisCacheExampleTest.java @@ -0,0 +1,41 @@ +package com.chinaunicom.mall.ebtp.cloud.redis.cache.example; + +import java.util.Objects; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.chinaunicom.mall.ebtp.cloud.redis.cache.example.service.ExampleService; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class RedisCacheExampleTest { + + private @Autowired ExampleService service; + + @Test + public void redisCacheTest() { + System.out.println(Objects.toString(service.queryById(1))); + +// // 相同的主键再次查询, 查看输入是否走了缓存 + System.out.println(Objects.toString(service.queryById(1))); +// +// // 使用其它id进行查询 +// System.out.println(Objects.toString(service.queryById(2))); +// +// // 修改数据, 检查缓存是否更新 +// System.out.println(Objects.toString(service.update(new User(2, "r42wer", 25)))); +// +// // 查询最新的数据 +// System.out.println(Objects.toString(service.queryById(2))); +// +// service.deleteById(2); +// +// // 测试数据删除时是否同时刷新了缓存 +// System.out.println(Objects.toString(service.queryById(2))); + } + +} diff --git a/examples/redis-example/src/main/resources/application-redis.yml b/examples/redis-example/src/main/resources/application-redis.yml index cb77b35..abfaff2 100644 --- a/examples/redis-example/src/main/resources/application-redis.yml +++ b/examples/redis-example/src/main/resources/application-redis.yml @@ -1,7 +1,3 @@ -server: - port: 8762 - max-http-header-size: 1000000 - spring: redis: database: 0 diff --git a/mall-ebtp-cloud-redis-starter/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/starter/config/JsonRedisSerializer.java b/mall-ebtp-cloud-redis-starter/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/starter/config/JsonRedisSerializer.java index aacdecb..ce858d4 100644 --- a/mall-ebtp-cloud-redis-starter/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/starter/config/JsonRedisSerializer.java +++ b/mall-ebtp-cloud-redis-starter/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/starter/config/JsonRedisSerializer.java @@ -9,82 +9,80 @@ import java.nio.charset.StandardCharsets; /** * redis序列化器 + * * @author xsx * @date 2019/7/5 * @since 1.8 */ public class JsonRedisSerializer implements RedisSerializer { - /** - * 序列化 - * @param t 对象 - * @return 返回字节数组 - * @throws SerializationException 序列化异常 - */ - @Override - public byte[] serialize(Object t) throws SerializationException { - if (t == null) { - return new byte[0]; - } - byte[] bytes; - if (this.isSimpleType(t)) { - bytes = t.toString().getBytes(StandardCharsets.UTF_8); - }else { - try { - bytes = JSONUtil.toJsonStr(t).getBytes(StandardCharsets.UTF_8); - } catch (Exception ex) { - throw new SerializationException("Could not serialize: " + ex.getMessage(), ex); - } - } - return bytes; - } + /** + * 序列化 + * + * @param t 对象 + * @return 返回字节数组 + * @throws SerializationException 序列化异常 + */ + @Override + public byte[] serialize(Object t) throws SerializationException { + if (t == null) { + return new byte[0]; + } + byte[] bytes; + if (this.isSimpleType(t)) { + bytes = t.toString().getBytes(StandardCharsets.UTF_8); + } else { + try { + bytes = JSONUtil.toJsonStr(t).getBytes(StandardCharsets.UTF_8); + } catch (Exception ex) { + throw new SerializationException("Could not serialize: " + ex.getMessage(), ex); + } + } + return bytes; + } - /** - * 反序列化 - * @param bytes 字节数组 - * @return 返回对象 - * @throws SerializationException 序列化异常 - */ - @Override - public Object deserialize(byte[] bytes) throws SerializationException { - return this.tryDeserialize(bytes); - } + /** + * 反序列化 + * + * @param bytes 字节数组 + * @return 返回对象 + * @throws SerializationException 序列化异常 + */ + @Override + public Object deserialize(byte[] bytes) throws SerializationException { + return this.tryDeserialize(bytes); + } - /** - * 尝试反序列化 - * @param bytes 字节数组 - * @return 返回对象 - * @throws SerializationException 序列化异常 - */ - private Object tryDeserialize(byte[] bytes) throws SerializationException { - if (bytes == null || bytes.length == 0) { - return null; - } - String str = new String(bytes, StandardCharsets.UTF_8); - if (JSONUtil.isJsonArray(str)) { - return JSONUtil.parseArray(str); - }else if (JSONUtil.isJsonObj(str)) { - return JSONUtil.parseObj(str); - }else { - return str; - } - } + /** + * 尝试反序列化 + * + * @param bytes 字节数组 + * @return 返回对象 + * @throws SerializationException 序列化异常 + */ + private Object tryDeserialize(byte[] bytes) throws SerializationException { + if (bytes == null || bytes.length == 0) { + return null; + } + String str = new String(bytes, StandardCharsets.UTF_8); + if (JSONUtil.isJsonArray(str)) { + return JSONUtil.parseArray(str); + } else if (JSONUtil.isJsonObj(str)) { + return JSONUtil.parseObj(str); + } + return str; + } - /** - * 是否简单类型 - * @param t 实体 - * @return 返回布尔值 - */ - private boolean isSimpleType(Object t) { - return SimpleType.BYTE.isValue(t) || - SimpleType.CHARACTER.isValue(t) || - SimpleType.SHORT.isValue(t) || - SimpleType.INTEGER.isValue(t) || - SimpleType.LONG.isValue(t) || - SimpleType.FLOAT.isValue(t) || - SimpleType.DOUBLE.isValue(t) || - SimpleType.BOOLEAN.isValue(t) || - SimpleType.BIGINTEGER.isValue(t) || - SimpleType.BIGDECIMAL.isValue(t); - } + /** + * 是否简单类型 + * + * @param t 实体 + * @return 返回布尔值 + */ + private boolean isSimpleType(Object t) { + return SimpleType.BYTE.isValue(t) || SimpleType.CHARACTER.isValue(t) || SimpleType.SHORT.isValue(t) + || SimpleType.INTEGER.isValue(t) || SimpleType.LONG.isValue(t) || SimpleType.FLOAT.isValue(t) + || SimpleType.DOUBLE.isValue(t) || SimpleType.BOOLEAN.isValue(t) || SimpleType.BIGINTEGER.isValue(t) + || SimpleType.BIGDECIMAL.isValue(t); + } } diff --git a/mall-ebtp-cloud-redis-starter/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/starter/config/cache/RedisCacheConfiguration.java b/mall-ebtp-cloud-redis-starter/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/starter/config/cache/RedisCacheConfiguration.java index 838c1de..695bd1b 100644 --- a/mall-ebtp-cloud-redis-starter/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/starter/config/cache/RedisCacheConfiguration.java +++ b/mall-ebtp-cloud-redis-starter/src/main/java/com/chinaunicom/mall/ebtp/cloud/redis/starter/config/cache/RedisCacheConfiguration.java @@ -15,6 +15,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.util.StringUtils; @@ -33,7 +34,6 @@ import com.chinaunicom.mall.ebtp.cloud.redis.starter.config.JsonRedisSerializer; @ConditionalOnMissingBean(CacheManager.class) @EnableConfigurationProperties({ CacheProperties.class }) public class RedisCacheConfiguration { - @Bean RedisCacheManager cacheManager(CacheProperties cacheProperties, ObjectProvider redisCacheConfiguration, @@ -41,13 +41,15 @@ public class RedisCacheConfiguration { RedisConnectionFactory redisConnectionFactory) { RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(determineConfiguration(cacheProperties, redisCacheConfiguration)); - // 缓存名称 + // 应用指定的缓存名称 List cacheNames = cacheProperties.getCacheNames(); + // 初始化缓存名称 if (!cacheNames.isEmpty()) { builder.initialCacheNames(new LinkedHashSet<>(cacheNames)); } // 以链模式自定义化builder redisCacheManagerBuilderCustomizers.orderedStream().forEach(customizer -> customizer.customize(builder)); + return new CacheManagerCustomizers(null).customize(builder.build()); } @@ -79,7 +81,7 @@ public class RedisCacheConfiguration { .defaultCacheConfig(); // 替换默认的序列化工具 config = config.serializeValuesWith( - RedisSerializationContext.SerializationPair.fromSerializer(new JsonRedisSerializer())); + RedisSerializationContext.SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(getClass().getClassLoader()))); if (redisProperties.getTimeToLive() != null) { config = config.entryTtl(redisProperties.getTimeToLive());// 缓存有效时间 }