Bläddra i källkod

redis guava -v0.01

(cherry picked from commit c85ff3f3f119d23246d39aeaa13919ed71b50e71)
(cherry picked from commit bedbbeef02ac1659e829d0ed3144d5a2efd3b4f1)
MOKASZ\lw12420 2 år sedan
förälder
incheckning
c52844a521

+ 2 - 0
launch-admin/src/main/java/com/webflux/launchadmin/LaunchAdminApplication.java

@@ -4,12 +4,14 @@ package com.webflux.launchadmin;
 import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableAsync;
 import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.transaction.annotation.EnableTransactionManagement;
 
 @EnableTransactionManagement
 @SpringBootApplication(scanBasePackages = "com.*")
 @EnableScheduling
+@EnableAsync
 public class LaunchAdminApplication {
 
     public static void main(String[] args) {

+ 99 - 0
launch-admin/src/main/java/com/webflux/launchadmin/redis/controller/test/UserController.java

@@ -0,0 +1,99 @@
+package com.webflux.launchadmin.redis.controller.test;
+
+
+import com.webflux.launchadmin.redis.service.test.UserService;
+
+import com.webflux.launchcommon.returnObj.RStatus;
+import com.weblux.launchredis.test.CacheService;
+import com.weblux.launchredis.test.User;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import reactor.core.publisher.Mono;
+
+/**
+ * redis
+ * @author lw12420
+ * @date 2024/07/17
+ */
+@RestController
+@RequestMapping("out/redis")
+public class UserController {
+
+    @Autowired
+    private UserService userService;
+    @Autowired
+    private CacheService cacheService;
+    /**
+     * get
+     * @param id
+     * @return {@link Mono}<{@link User}>
+     */
+    @GetMapping("/{id}")
+    public Mono<User> getUserById(@PathVariable String id) {
+        return userService.getUserById(id);
+    }
+
+    /**
+     * save
+     * @param user
+     * @return {@link Mono}<{@link Boolean}>
+     */
+    @PostMapping
+    public Mono<Boolean> createUser(@RequestBody User user) {
+        return userService.saveUser(user);
+    }
+
+
+    /**
+     * putCache
+     *
+     * @param key
+     * @param value
+     * @return {@link Mono}<{@link Void}>
+     */
+    @GetMapping("/cache")
+    public Mono<RStatus<Boolean>> putCache(@RequestParam("key") String key, @RequestParam("value") String value) {
+        return cacheService.put(key, value);
+    }
+
+    /**
+     * getCache
+     * @param key
+     * @return {@link Mono}<{@link Object}>
+     */
+    @GetMapping("/cache/{key}")
+    public Mono<Object> getCache(@PathVariable String key) {
+        return cacheService.get(key, Object.class);
+    }
+    /**
+     * getCache USer
+     * @param key
+     * @return {@link Mono}<{@link Object}>
+     */
+    @GetMapping("/cacheUser/{key}")
+    public Mono<User> getCacheUSer(@PathVariable String key) {
+        return cacheService.get(key, User.class);
+    }
+
+    /**
+     * USerSave
+     * @return {@link Mono}<{@link RStatus}<{@link Boolean}>>
+     */
+    @GetMapping("/cacheUser")
+    public Mono<RStatus<Boolean>> putUserCache() {
+        User user = new User();
+        user.setId("1");
+        user.setName("1");
+        user.setAge(1);
+        return cacheService.put("2", user);
+    }
+    /**
+     * removeCache
+     * @param key
+     * @return {@link Mono}<{@link Void}>
+     */
+    @GetMapping("/cache/remove/{key}")
+    public Mono<Void> removeCache(@PathVariable String key) {
+        return cacheService.remove(key);
+    }
+}

+ 60 - 0
launch-admin/src/main/java/com/webflux/launchadmin/redis/service/test/UserService.java

@@ -0,0 +1,60 @@
+package com.webflux.launchadmin.redis.service.test;
+
+
+import cn.hutool.core.bean.BeanUtil;
+import cn.hutool.json.JSONObject;
+import cn.hutool.json.JSONUtil;
+
+
+import com.weblux.launchredis.test.User;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.ReactiveRedisOperations;
+import org.springframework.data.redis.core.ReactiveRedisTemplate;
+import org.springframework.data.redis.util.ByteUtils;
+import org.springframework.stereotype.Service;
+import reactor.core.publisher.Mono;
+
+import java.nio.ByteBuffer;
+import java.time.Duration;
+import java.util.logging.Level;
+
+@Service
+public class UserService {
+
+
+    @Autowired
+    ReactiveRedisOperations<String, User> typedOperations;
+    @Autowired
+    ReactiveRedisOperations<String, Object> objectOperations;
+    private final String USER_KEY_PREFIX = "user:";
+
+    public Mono<User> getUserById(String id) {
+        return typedOperations.opsForValue().get(USER_KEY_PREFIX + id);
+
+    }
+
+    /**
+     * 案例
+     * @return
+     */
+    public Mono<Boolean> saveOther() {
+        var get = objectOperations
+                .execute(conn -> conn.stringCommands().get(ByteBuffer.wrap("homer".getBytes()))) //
+                .map(ByteUtils::getBytes) //
+                .map(String::new);
+
+        var queue = "foo";
+
+        var listOperations = objectOperations.opsForList();
+        var blpop = listOperations //
+                .leftPop(queue, Duration.ofSeconds(30)) //
+                .log("example.springdata.redis", Level.INFO);
+        Mono<Long> longMono = listOperations.leftPush(queue, "1");
+
+        return  Mono.just(true);
+    }
+
+    public Mono<Boolean> saveUser(User user) {
+        return typedOperations.opsForValue().set(USER_KEY_PREFIX + user.getId(), user);
+    }
+}

+ 1 - 1
launch-admin/src/main/resources/application-dev.yml

@@ -7,7 +7,7 @@ spring:
       database: 0
       timeout: 10000
   r2dbc:
-    url: r2dbcs:mysql://rm-uf6xylut5n33hb3o5ro.mysql.rds.aliyuncs.com:3306/wx_share_test?serverZoneId=GMT%2b8&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&ssl=false&sslMode=DISABLED
+    url: r2dbcs:mysql://rm-uf6xylut5n33hb3o5ro.mysql.rds.aliyuncs.com:3306/wx_share_8?serverZoneId=GMT%2b8&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&ssl=false&sslMode=DISABLED
     username: wx_share_liuwei
     password: Wx_ShARe56578AwCH
 

+ 3 - 3
launch-admin/src/main/resources/smart-doc.json

@@ -2,14 +2,14 @@
   "outPath": "F://smart_doc_dome",
   "serverUrl": "http://127.0.0.1:9201",
   "isStrict": false,
-  "packageFilters": "com.webflux.launchadmin.mysql.controller",
+  "packageFilters": "com.webflux.launchadmin.mysql.controller,com.webflux.launchadmin.redis.controller",
   "projectName": "API",
   "appKey": "",
   "appToken": "7d846275fe5b46988e32d7c637838d07",
   "secret": "",
   "openUrl": "http://localhost:7788/api",
   "debugEnvName": "测试环境",
-  "debugEnvUrl": "http://127.0.0.1:9201",
+  "debugEnvUrl": "http://127.0.0.1:8800",
   "author": "liuwei",
   "sortByTitle": true,
   "requestHeaders": [
@@ -17,7 +17,7 @@
       "name": "Cookie",
       "type": "string",
       "desc": "你的xxl_sso_sessionid",
-      "value": "xxl_sso_sessionid=163d1c98_140055b8ccc444ba8b1b4acb72cd65ad",
+      "value": "xxl_sso_sessionid=163d1c98_e913d403bd954587b5629e215b112cf1",
       "required": false,
       "since": "-"
     }

+ 14 - 0
launch-common/src/main/java/com/webflux/launchcommon/virtual/AsyncService.java

@@ -0,0 +1,14 @@
+package com.webflux.launchcommon.virtual;
+
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Service;
+
+@Service
+public class AsyncService {
+
+    @Async("virtualThreadPoolExecutor")
+    public void executeAsyncTask() {
+        System.out.println("Executing task in virtual thread: " + Thread.currentThread());
+        // 这里可以执行你的异步任务
+    }
+}

+ 17 - 0
launch-common/src/main/java/com/webflux/launchcommon/virtual/VirtualThreadPoolConfig.java

@@ -0,0 +1,17 @@
+package com.webflux.launchcommon.virtual;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+
+@Configuration
+public class VirtualThreadPoolConfig {
+
+    @Bean(name = "virtualThreadPoolExecutor")
+    public Executor virtualThreadPoolExecutor() {
+        return Executors.newVirtualThreadPerTaskExecutor();
+    }
+}

+ 12 - 1
launch-redis/pom.xml

@@ -23,7 +23,18 @@
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
         </dependency>
-
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.data</groupId>
+            <artifactId>spring-data-redis</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+        </dependency>
         <dependency>
             <groupId>com.launch.webflux</groupId>
             <artifactId>launch-common</artifactId>

+ 19 - 0
launch-redis/src/main/java/com/weblux/launchredis/cacheConfig/CacheConfig.java

@@ -0,0 +1,19 @@
+package com.weblux.launchredis.cacheConfig;
+
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+
+@Configuration
+public class CacheConfig {
+
+    @Bean
+    public Cache<String, Object> guavaCache() {
+        return CacheBuilder.newBuilder()
+                .expireAfterWrite(java.time.Duration.ofMinutes(10))  // 设置缓存过期时间
+                .maximumSize(1000)  // 设置缓存最大容量
+                .build();
+    }
+}

+ 31 - 2
launch-redis/src/main/java/com/weblux/launchredis/config/ReactiveRedisConfig.java

@@ -3,10 +3,12 @@ package com.weblux.launchredis.config;
 import com.fasterxml.jackson.annotation.JsonAutoDetect;
 import com.fasterxml.jackson.annotation.PropertyAccessor;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.weblux.launchredis.test.User;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
 import org.springframework.data.redis.core.ReactiveRedisTemplate;
+import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
 import org.springframework.data.redis.serializer.RedisSerializationContext;
 import org.springframework.data.redis.serializer.StringRedisSerializer;
@@ -37,9 +39,36 @@ public class ReactiveRedisConfig {
         return builder.build();
     }
 
+    /**
+     * Configures a {@link ReactiveRedisTemplate} with {@link String} keys and a typed
+     * {@link Jackson2JsonRedisSerializer}.
+     */
     @Bean
-    public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory connectionFactory) {
-        return new ReactiveRedisTemplate<>(connectionFactory,redisSerializationContext());
+    public ReactiveRedisTemplate<String, User> reactiveJsonUserRedisTemplate(
+            ReactiveRedisConnectionFactory connectionFactory) {
+
+        var serializer = new Jackson2JsonRedisSerializer<User>(User.class);
+        RedisSerializationContext.RedisSerializationContextBuilder<String, User> builder = RedisSerializationContext
+                .newSerializationContext(new StringRedisSerializer());
+
+        var serializationContext = builder.value(serializer).build();
+
+        return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
     }
+    @Bean
+    public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
+        RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
+                .<String, Object>newSerializationContext(new StringRedisSerializer())
+                .hashKey(new StringRedisSerializer())
+                .hashValue(new Jackson2JsonRedisSerializer<>(Object.class))
+                .build();
+
+        return new ReactiveRedisTemplate<>(factory, serializationContext);
+    }
+
+//    @Bean
+//    public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory connectionFactory) {
+//        return new ReactiveRedisTemplate<>(connectionFactory,redisSerializationContext());
+//    }
 }
 

+ 28 - 0
launch-redis/src/main/java/com/weblux/launchredis/test/CacheService.java

@@ -0,0 +1,28 @@
+package com.weblux.launchredis.test;
+
+import com.google.common.cache.Cache;
+import com.webflux.launchcommon.returnObj.RStatus;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import reactor.core.publisher.Mono;
+
+@Service
+public class CacheService {
+
+    @Autowired
+    private Cache<String, Object> guavaCache;
+
+    public Mono<RStatus<Boolean>> put(String key, Object value) {
+        guavaCache.put(key, value);
+        return RStatus.success(Mono.just(true));
+    }
+
+    public <T> Mono<T> get(String key, Class<T> type) {
+        return Mono.justOrEmpty(type.cast(guavaCache.getIfPresent(key)));
+    }
+
+    public Mono<Void> remove(String key) {
+        guavaCache.invalidate(key);
+        return Mono.empty();
+    }
+}

+ 17 - 0
launch-redis/src/main/java/com/weblux/launchredis/test/User.java

@@ -0,0 +1,17 @@
+package com.weblux.launchredis.test;
+
+import lombok.Data;
+import org.springframework.data.annotation.Id;
+import org.springframework.data.redis.core.RedisHash;
+
+import java.io.Serializable;
+
+@Data
+@RedisHash("User")
+public class User implements Serializable {
+    private static final long serialVersionUID = 1L;
+    @Id
+    private String id;
+    private String name;
+    private int age;
+}

+ 9 - 1
pom.xml

@@ -6,7 +6,7 @@
     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
-        <version>3.2.0</version>
+        <version>3.2.1</version>
         <relativePath/> <!-- lookup parent from repository -->
     </parent>
 
@@ -35,10 +35,18 @@
         <cola-component-dto>4.3.2</cola-component-dto>
         <revision>2022.0.0.0</revision>
         <spring-data-bom>2023.1.0</spring-data-bom>
+        <guava-version>31.1-jre</guava-version>
     </properties>
 
     <dependencyManagement>
         <dependencies>
+            <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
+            <dependency>
+                <groupId>com.google.guava</groupId>
+                <artifactId>guava</artifactId>
+                <version>${guava-version}</version>
+            </dependency>
+
             <dependency>
                 <groupId>org.springframework.data</groupId>
                 <artifactId>spring-data-bom</artifactId>