tanlie преди 1 година
родител
ревизия
f4d7f496e6

+ 2 - 0
demo/.gitattributes

@@ -0,0 +1,2 @@
+/mvnw text eol=lf
+*.cmd text eol=crlf

+ 33 - 0
demo/.gitignore

@@ -0,0 +1,33 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/

+ 97 - 0
demo/pom.xml

@@ -0,0 +1,97 @@
+<?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>3.4.3</version>
+		<relativePath/> <!-- lookup parent from repository -->
+	</parent>
+	<groupId>com.digital</groupId>
+	<artifactId>demo</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+	<name>demo</name>
+	<description>demo</description>
+	<url/>
+	<licenses>
+		<license/>
+	</licenses>
+	<developers>
+		<developer/>
+	</developers>
+	<scm>
+		<connection/>
+		<developerConnection/>
+		<tag/>
+		<url/>
+	</scm>
+	<properties>
+		<java.version>17</java.version>
+	</properties>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-data-redis</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-web</artifactId>
+		</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>
+		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
+		<dependency>
+			<groupId>org.apache.commons</groupId>
+			<artifactId>commons-lang3</artifactId>
+			<version>3.17.0</version>
+		</dependency>
+	</dependencies>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-compiler-plugin</artifactId>
+				<configuration>
+					<annotationProcessorPaths>
+						<path>
+							<groupId>org.springframework.boot</groupId>
+							<artifactId>spring-boot-configuration-processor</artifactId>
+						</path>
+						<path>
+							<groupId>org.projectlombok</groupId>
+							<artifactId>lombok</artifactId>
+						</path>
+					</annotationProcessorPaths>
+				</configuration>
+			</plugin>
+			<plugin>
+				<groupId>org.springframework.boot</groupId>
+				<artifactId>spring-boot-maven-plugin</artifactId>
+				<configuration>
+					<excludes>
+						<exclude>
+							<groupId>org.projectlombok</groupId>
+							<artifactId>lombok</artifactId>
+						</exclude>
+					</excludes>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

+ 13 - 0
demo/src/main/java/com/example/demo/DemoApplication.java

@@ -0,0 +1,13 @@
+package com.example.demo;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class DemoApplication {
+
+	public static void main(String[] args) {
+		SpringApplication.run(DemoApplication.class, args);
+	}
+
+}

+ 83 - 0
demo/src/main/java/com/example/demo/config/redis/RedisConfig.java

@@ -0,0 +1,83 @@
+package com.example.demo.config.redis;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.cache.RedisCacheConfiguration;
+import org.springframework.data.redis.cache.RedisCacheManager;
+import org.springframework.data.redis.cache.RedisCacheWriter;
+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.RedisSerializationContext;
+import org.springframework.data.redis.serializer.RedisSerializer;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+import java.net.UnknownHostException;
+import java.time.Duration;
+
+/**
+ * Description:
+ *
+ * @author tanlie
+ * Date: 2024/1/9 9:07
+ */
+@EnableCaching
+@Configuration
+public class RedisConfig {
+    /**
+     * 缓存管理器
+     *
+     * @param factory
+     * @return
+     */
+    @Bean
+    @SuppressWarnings("all")
+    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
+        ObjectMapper om = new ObjectMapper();
+        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
+        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
+        // 解决查询缓存转换异常的问题
+        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+        jackson2JsonRedisSerializer.setObjectMapper(om);
+        // 配置序列化(解决乱码的问题)
+        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
+                .entryTtl(Duration.ofMillis(-1))
+                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
+                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
+                .disableCachingNullValues();
+        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(factory);
+
+        return new RedisConfigCacheManager(cacheWriter, config);
+    }
+
+    //重写template配置累
+    @Bean
+    @SuppressWarnings("all")
+    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) throws UnknownHostException {
+
+        RedisTemplate<String, Object> template = new RedisTemplate();
+        template.setConnectionFactory(factory);
+        //json序列化
+        Jackson2JsonRedisSerializer<Object> 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);
+        template.setHashKeySerializer(stringRedisSerializer);  //hash key也采用string
+        //value 采用json
+        template.setValueSerializer(jackson2JsonRedisSerializer);
+        template.setHashValueSerializer(jackson2JsonRedisSerializer);
+
+        template.afterPropertiesSet();
+        return template;
+    }
+}

+ 54 - 0
demo/src/main/java/com/example/demo/config/redis/RedisConfigCacheManager.java

@@ -0,0 +1,54 @@
+package com.example.demo.config.redis;
+
+
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.data.redis.cache.*;
+import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.RedisSerializationContext;
+
+import java.time.Duration;
+
+/**
+ * Description:
+ *
+ * @author tanlie
+ * Date: 2024/9/5 11:01
+ */
+public class RedisConfigCacheManager extends RedisCacheManager {
+
+    private static final CacheKeyPrefix DEFAULT_CACHE_KEY_PREFIX = cacheName -> cacheName + ":";
+
+    public RedisConfigCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
+        super(cacheWriter, defaultCacheConfiguration);
+    }
+
+    private static final RedisSerializationContext.SerializationPair<Object> DEFAULT_PAIR = RedisSerializationContext.SerializationPair
+            .fromSerializer(new GenericJackson2JsonRedisSerializer());
+
+    /**
+     * @param name
+     * @param cacheConfig
+     * @return
+     */
+    @Override
+    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
+        final int lastIndexOf = StringUtils.lastIndexOf(name, '#');
+        if (lastIndexOf > -1) {
+            final String ttl = StringUtils.substring(name, lastIndexOf + 1);
+            final Duration duration = Duration.ofSeconds(Long.parseLong(ttl));
+            cacheConfig = cacheConfig.entryTtl(duration);
+            //修改缓存key和value值的序列化方式
+            cacheConfig = cacheConfig.computePrefixWith(DEFAULT_CACHE_KEY_PREFIX)
+                    .serializeValuesWith(DEFAULT_PAIR);
+            final String cacheName = StringUtils.substring(name, 0, lastIndexOf);
+            return super.createRedisCache(cacheName, cacheConfig);
+        } else {
+            //修改缓存key和value值的序列化方式
+            cacheConfig = cacheConfig.computePrefixWith(DEFAULT_CACHE_KEY_PREFIX)
+                    .serializeValuesWith(DEFAULT_PAIR);
+            return super.createRedisCache(name, cacheConfig);
+        }
+    }
+
+
+}

+ 40 - 0
demo/src/main/java/com/example/demo/config/redis/RedisKeyEnum.java

@@ -0,0 +1,40 @@
+package com.example.demo.config.redis;
+
+import lombok.Getter;
+
+/**
+ * Description:
+ *
+ * @author tanlie
+ * Date: 2024/1/9 9:12
+ */
+@Getter
+public enum RedisKeyEnum {
+
+    //登录相关
+    CAPTCHA("captcha:", "验证码", 300),
+
+    CURRENT_USER("current_user:", "当前用户", 3600 * 12),
+    CURRENT_USER_TOKEN("current_user_token:", "当前用户token", 3600 * 12),
+
+    LOGIN_FAIL("login_fail:", "登录错误尝试", 3600 * 24),
+    DICTIONARY("dictionary", "字典", 2 * 3600),
+
+    // 行销行政编码
+    MARKET_MAP_USER_INFO("MARKET_MAP_USER_INFO:", "行销工具用户信息", 600),
+    MARKET_MAP_NAME_BY_CODES("MARKET_MAP_NAME_BY_CODES:", "行销行政编码", 3600 * 7 * 24),
+
+    // 验证码相关
+    SMS_COUNT("sms_count:", "每半个小时发送的短信数量", 1800),
+    SMS_VALIDATE("sms_validate:", "短信验证码", 300);
+
+    RedisKeyEnum(String code, String msg, Integer expireTime) {
+        this.code = code;
+        this.msg = msg;
+        this.expireTime = expireTime;
+    }
+
+    private final String code;
+    private final String msg;
+    private final Integer expireTime;
+}

+ 12 - 0
demo/src/main/resources/application.yml

@@ -0,0 +1,12 @@
+server:
+  port: 8080
+spring:
+  application:
+    name: demo-application
+
+  data:
+    redis:
+      host: 116.8.109.23
+      port: 40071
+      password: "XinchanR@2022###"
+      database: 8

+ 13 - 0
demo/src/test/java/com/example/demo/DemoApplicationTests.java

@@ -0,0 +1,13 @@
+package com.example.demo;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class DemoApplicationTests {
+
+	@Test
+	void contextLoads() {
+	}
+
+}

+ 24 - 0
demo/src/test/java/com/example/demo/config/redis/RedisConfigTest.java

@@ -0,0 +1,24 @@
+package com.example.demo.config.redis;
+
+import jakarta.annotation.Resource;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.data.redis.core.RedisTemplate;
+
+/**
+ * @description
+ * @date 2025-03-12 17:03
+ **/
+@SpringBootTest
+class RedisConfigTest {
+    @Resource
+    RedisTemplate<String, Object> redisTemplate;
+
+    @Test
+    void StringTest() {
+        redisTemplate.opsForValue().set("hello", "world");
+        System.out.println(redisTemplate.opsForValue().get("hello"));
+
+    }
+
+}