懒羊羊
2024-03-23 5239031423deb80a31ac328838240adc51594804
提交 | 用户 | 时间
e57a89 1 package com.jcdm.framework.config;
2
3 import org.springframework.cache.annotation.CachingConfigurerSupport;
4 import org.springframework.cache.annotation.EnableCaching;
5 import org.springframework.context.annotation.Bean;
6 import org.springframework.context.annotation.Configuration;
7 import org.springframework.data.redis.connection.RedisConnectionFactory;
8 import org.springframework.data.redis.core.RedisTemplate;
9 import org.springframework.data.redis.core.script.DefaultRedisScript;
10 import org.springframework.data.redis.serializer.StringRedisSerializer;
11
12 /**
13  * redis配置
14  * 
15  * @author jc
16  */
17 //@Configuration
18 //@EnableCaching
19 public class RedisConfig extends CachingConfigurerSupport
20 {
21 //    @Bean
22     @SuppressWarnings(value = { "unchecked", "rawtypes" })
23     public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
24     {
25         RedisTemplate<Object, Object> template = new RedisTemplate<>();
26         template.setConnectionFactory(connectionFactory);
27
28         FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
29
30         // 使用StringRedisSerializer来序列化和反序列化redis的key值
31         template.setKeySerializer(new StringRedisSerializer());
32         template.setValueSerializer(serializer);
33
34         // Hash的key也采用StringRedisSerializer的序列化方式
35         template.setHashKeySerializer(new StringRedisSerializer());
36         template.setHashValueSerializer(serializer);
37
38         template.afterPropertiesSet();
39         return template;
40     }
41
42 //    @Bean
43     public DefaultRedisScript<Long> limitScript()
44     {
45         DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
46         redisScript.setScriptText(limitScriptText());
47         redisScript.setResultType(Long.class);
48         return redisScript;
49     }
50
51     /**
52      * 限流脚本
53      */
54     private String limitScriptText()
55     {
56         return "local key = KEYS[1]\n" +
57                 "local count = tonumber(ARGV[1])\n" +
58                 "local time = tonumber(ARGV[2])\n" +
59                 "local current = redis.call('get', key);\n" +
60                 "if current and tonumber(current) > count then\n" +
61                 "    return tonumber(current);\n" +
62                 "end\n" +
63                 "current = redis.call('incr', key)\n" +
64                 "if tonumber(current) == 1 then\n" +
65                 "    redis.call('expire', key, time)\n" +
66                 "end\n" +
67                 "return tonumber(current);";
68     }
69 }