注入redisjava
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisPassword; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig;redis
import java.time.Duration;spring
/** */ @Configuration public class RedisNoRepeatSubmitConfiguration { @Value("${spring.redisNoRepeatSubmit.host:192.168.0.219}") private String redisHost;apache
@Value("${spring.redisNoRepeatSubmit.port:6379}") private int redisPort; @Value("${spring.redisNoRepeatSubmit.timeout:20000}") private int redisTimeout; @Value("${spring.redisNoRepeatSubmit.password:sunvua1028}") private String redisAuth; @Value("${spring.redisNoRepeatSubmit.database:0}") private int redisDb; @Value("${spring.redisNoRepeatSubmit.pool.max-active:20}") private int maxActive; @Value("${spring.redisNoRepeatSubmit.pool.max-wait:-1}") private int maxWait; @Value("${spring.redisNoRepeatSubmit.pool.max-idle:8}") private int maxIdle; @Value("${spring.redisNoRepeatSubmit.pool.min-idle:0}") private int minIdle; @Bean(name="NoRepeatSubmit") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 配置鏈接工廠 JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(maxActive); poolConfig.setMaxIdle(maxIdle); poolConfig.setMaxWaitMillis(maxWait); poolConfig.setMinIdle(minIdle); poolConfig.setTestOnBorrow(true); poolConfig.setTestOnReturn(false); poolConfig.setTestWhileIdle(true); JedisClientConfiguration clientConfig = JedisClientConfiguration.builder() .usePooling().poolConfig(poolConfig).and().readTimeout(Duration.ofMillis(redisTimeout)).build(); // 單點redis RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration(); // 哨兵redis // RedisSentinelConfiguration redisConfig = new RedisSentinelConfiguration(); // 集羣redis // RedisClusterConfiguration redisConfig = new RedisClusterConfiguration(); redisConfig.setHostName(redisHost); redisConfig.setPassword(RedisPassword.of(redisAuth)); redisConfig.setPort(redisPort); redisConfig.setDatabase(redisDb); factory=new JedisConnectionFactory(redisConfig,clientConfig); template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修飾符範圍,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,好比String,Integer等會跑出異常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值採用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer來序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 設置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); //開啓事務 與 @Transactional(rollbackFor = Exception.class) 一塊兒使用 template.setEnableTransactionSupport(true); return template; }
} //建立 註解 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;json
/**緩存
建立表單驗證aop import com.sunvua.coeus.core.columnaccess.annotation.NoRepeatSubmit; import com.sunvua.coeus.core.constant.SysConstants; import com.sunvua.coeus.core.json.JsonResult; import com.sunvua.coeus.ext.common.util.HttpUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component;app
import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.concurrent.TimeUnit;測試
/**ui
@Author jscurl
防止表達提交aop **/ @Aspect @Component public class NoRepeatSubmitAop { private Log logger = LogFactory.getLog(getClass()); @Resource(name="NoRepeatSubmit") private RedisTemplate<String, Object> redisTemplate; @Autowired protected HttpServletRequest request; @Around(value = "@annotation(nrs)") public Object arround(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) { ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue(); try { String userId = HttpUtils.getRequestUserId(); if(userId==null||userId.equals(SysConstants.USER_ANONYMOUS)){ logger.error("沒有登陸權限"); return JsonResult.fail("沒有登陸權限"); } String key ="NoRepeatSubmit:"+ userId + "&" + request.getServletPath(); if (opsForValue.get(key) == null) {// 若是緩存中有這個url視爲重複提交 // Object o = pjp.proceed(); opsForValue.set(key, key, Long.valueOf(nrs.value()), TimeUnit.SECONDS); Object result = pjp.proceed(); //執行方法 return result; } else { logger.error("重複提交"); return JsonResult.fail("重複提交"); } } catch (Throwable e) { logger.error("重複提交{}",e); return JsonResult.fail("沒有登陸權限"); }
}
}
測試方法 @RequestMapping("/test") @NoRepeatSubmit 3秒不可提交 public String test(){ return "success" ; }
@RequestMapping("/test2") @NoRepeatSubmit("100") 100秒不可重複提交 public JsonResult test2(){ return JsonResult.success("success") ; }