依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.43</version>
</dependency>
配置yml
spring:
redis:
host: xxx.xxx.xxx.xxx
port: 6379
database: 3
password:
timeout: 10s
lettuce:
pool:
min-idle: 0
max-idle: 8
max-active: 8
max-wait: -1ms
配置类
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
@Bean
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
{
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
@Bean
public DefaultRedisScript<Long> limitScript()
{
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptText(limitScriptText());
redisScript.setResultType(Long.class);
return redisScript;
}
private String limitScriptText()
{
return "local key = KEYS[1]\n" +
"local count = tonumber(ARGV[1])\n" +
"local time = tonumber(ARGV[2])\n" +
"local current = redis.call('get', key);\n" +
"if current and tonumber(current) > count then\n" +
" return tonumber(current);\n" +
"end\n" +
"current = redis.call('incr', key)\n" +
"if tonumber(current) == 1 then\n" +
" redis.call('expire', key, time)\n" +
"end\n" +
"return tonumber(current);";
}
}
FastJson2JsonRedisSerializer
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
{
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private Class<T> clazz;
public FastJson2JsonRedisSerializer(Class<T> clazz)
{
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException
{
if (t == null)
{
return new byte[0];
}
return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException
{
if (bytes == null || bytes.length <= 0)
{
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
}
}
RedisCache工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
@Autowired
public RedisTemplate redisTemplate;
public Long increment(final String key)
{
return redisTemplate.opsForValue().increment(key);
}
public <T> void setCacheObject(final String key, final T value)
{
redisTemplate.opsForValue().set(key, value);
}
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
{
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
public boolean expire(final String key, final long timeout)
{
return expire(key, timeout, TimeUnit.SECONDS);
}
public boolean expire(final String key, final long timeout, final TimeUnit unit)
{
return redisTemplate.expire(key, timeout, unit);
}
public long getExpire(final String key)
{
return redisTemplate.getExpire(key);
}
public Boolean hasKey(String key)
{
return redisTemplate.hasKey(key);
}
public <T> T getCacheObject(final String key)
{
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
public boolean deleteObject(final String key)
{
return redisTemplate.delete(key);
}
public boolean deleteObject(final Collection collection)
{
return redisTemplate.delete(collection) > 0;
}
public <T> long setCacheList(final String key, final List<T> dataList)
{
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
public <T> List<T> getCacheList(final String key)
{
return redisTemplate.opsForList().range(key, 0, -1);
}
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
{
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext())
{
setOperation.add(it.next());
}
return setOperation;
}
public <T> Set<T> getCacheSet(final String key)
{
return redisTemplate.opsForSet().members(key);
}
public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
{
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
public <T> Map<String, T> getCacheMap(final String key)
{
return redisTemplate.opsForHash().entries(key);
}
public <T> void setCacheMapValue(final String key, final String hKey, final T value)
{
redisTemplate.opsForHash().put(key, hKey, value);
}
public <T> T getCacheMapValue(final String key, final String hKey)
{
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
{
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
public boolean deleteCacheMapValue(final String key, final String hKey)
{
return redisTemplate.opsForHash().delete(key, hKey) > 0;
}
public Collection<String> keys(final String pattern)
{
return redisTemplate.keys(pattern);
}
}
使用工具类
@Api(tags = "上传数据")
@RestController
@Validated
@RequestMapping("/data")
public class DataController {
@Resource
private RedisCache redisCache;
@ApiOperation(value = "缺陷数据上传",tags = "缺陷数据上传")
@PostMapping("/defect")
public AjaxResult defect(@RequestBody Defect defect ) {
if("漏插".equals(defect.getType())){
Integer lochaNum = redisCache.getCacheObject("lochaNum");
if(lochaNum == null){
redisCache.setCacheObject("lochaNum",1);
}else {
redisCache.deleteObject("lochaNum");
redisCache.setCacheObject("lochaNum",lochaNum+1);
}
}
if("虚插".equals(defect.getType())){
Integer xuchaNum = redisCache.getCacheObject("xuchaNum");
if(xuchaNum == null){
redisCache.setCacheObject("xuchaNum",1);
}else {
redisCache.deleteObject("xuchaNum");
redisCache.setCacheObject("xuchaNum",xuchaNum+1);
}
}
List<Defect> defects = redisCache.getCacheList("defects");
if(CollectionUtils.isEmpty(defects)){
defects = new ArrayList<>();
}
defects.add(defect);
redisCache.deleteObject("defects");
if(defects.size()>10){
redisCache.setCacheList("defects",defects.subList(defects.size()-10,defects.size()));
}else {
redisCache.setCacheList("defects",defects);
}
return AjaxResult.success();
}
@ApiOperation(value = "入侵数据上传",tags = "入侵数据上传")
@PostMapping("/intrusion")
public AjaxResult intrusion(@RequestBody Intrusion intrusion ) {
List<Intrusion> intrusions = redisCache.getCacheList("intrusions");
if(CollectionUtils.isEmpty(intrusions)){
intrusions = new ArrayList<>();
}
intrusions.add(intrusion);
redisCache.deleteObject("intrusions");
if(intrusions.size()>10){
redisCache.setCacheList("intrusions",intrusions.subList(intrusions.size()-10,intrusions.size()));
}else {
redisCache.setCacheList("intrusions",intrusions);
}
return AjaxResult.success();
}
@ApiOperation(value = "获取缺陷数据",tags = "获取缺陷数据")
@PostMapping("/getDefect")
public AjaxResult getDefect() {
List<Defect> defects = redisCache.getCacheList("defects");
return AjaxResult.success(defects);
}
@ApiOperation(value = "获取入侵数据",tags = "获取入侵数据")
@PostMapping("/getIntrusion")
public AjaxResult getIntrusion() {
List<Intrusion> intrusions = redisCache.getCacheList("intrusions");
return AjaxResult.success(intrusions);
}
@ApiOperation(value = "获取缺陷占比",tags = "获取缺陷占比")
@PostMapping("/getDefectPer")
public AjaxResult getDefectPer() {
Integer lochaNum = redisCache.getCacheObject("lochaNum");
Integer xuchaNum = redisCache.getCacheObject("xuchaNum");
Integer total = lochaNum+xuchaNum;
String lochaPer = percent(lochaNum, total);
String xuchaPer = percent(xuchaNum, total);
HashMap<String, Object> resultMap = new HashMap<>();
resultMap.put("lochaPer",lochaPer);
resultMap.put("xuchaPer",xuchaPer);
return AjaxResult.success(resultMap);
}
public String percent(int num1,int num2){
String rate="0.00%";
String format="0.00";
if(num2 != 0 && num1 != 0){
DecimalFormat dec = new DecimalFormat(format);
rate = dec.format((double) num1 / num2*100)+"%";
while(true){
if(rate.equals(format+"%")){
format=format+"0";
DecimalFormat dec1 = new DecimalFormat(format);
rate = dec1.format((double) num1 / num2*100)+"%";
}else {
break;
}
}
}else if(num1 != 0 && num2 == 0){
rate = "100%";
}
return rate;
}
}