1.引入redis依赖
在common下的pom文件中引入Redis依赖
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-pool2
2.配置文件配置Redis 在项目配置文件中配置Redis
spring.redis.database=15
spring.redis.host=10.196.1.62
spring.redis.port=7019
spring.redis.password=gpSPcwzK
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=5s
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
3.设置Redis 3.1定义Redis的key 在common文件夹下创建cache文件夹,定义KeyConstans.java文件
public class KeyConstans {/**
* 存储预警类型编码与名称的对应关系
* 初始化时执行0
*/
public static String DISTKEY = "SSCVHB:DISTLIST:ALARM";
/**
* 存储预警类型编码与父类名称的对应关系
* 初始化时执行0
*/
public static String DISTPARENTKEY = "SSCVHB:DISTLIST:PARENT:ALARM";
}
3.2设置RedisConfig 在cache文件夹下定义RedisConfig.java文件
package com.hikvision.isc.common.cache;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {/*@Bean
public JedisConnectionFactory redisConnectionFactory() {RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);
config.setPassword(password);
return new JedisConnectionFactory(config);
}*/@Bean
@SuppressWarnings("all")
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer 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);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
3.3 定义Redis的set、get等方法 在cache文件夹下定义RedisUtils.java文件
package com.hikvision.isc.common.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Service
public class RedisUtils {
private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);
@Autowired
private RedisTemplate redisTemplate;
/**
* 获取所有key
*/
public Set getKeyAll() {
Set keySet = redisTemplate.keys("*");
return keySet;
}/**
* 模糊搜索key
*/
public Set getKey(String key) {
String s = "*" + key + "*";
Set keySet = redisTemplate.keys(s);
return keySet;
}/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}/**
* 写入缓存设置时效时间
* key过期后,再获取key就是null
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}/**
* 设置key的过期时间
*/
public void expireKey(String key, Long l, TimeUnit timeUnit) {
redisTemplate.expire(key, l, timeUnit);
}/**
* 批量删除对应的value
*
* @param keys
*/public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}/**
* 批量删除key
*
* @param pattern
*/public void removePattern(final String pattern) {
Set keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}/**
* 删除对应的value
*
* @param key
*/public void remove(final String key) {
logger.info("redis删除key:{}", key);
if (exists(key)) {
redisTemplate.delete(key);
}
}/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}/**
* 断缓存中是否有对应的filed
*/public boolean hexists(final String key, String field) {
return redisTemplate.opsForHash().hasKey(key, field);
}/**
* 读取缓存
*
* @param key
* @return
*/public Object get(final String key) {
Object result = null;
ValueOperations operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/public void hmSet(String key, Object hashKey, Object value) {
HashOperations hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}public void hmSet(String key, Object hashKey, Object value, Long expireTime, TimeUnit timeUnit) {
HashOperations hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
redisTemplate.expire(key, expireTime, timeUnit);
}/**
* 哈希获取数据
*
* @param key
* @param hashKey
* @return
*/public Object hmGet(String key, Object hashKey) {
HashOperations hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}/**
* 获取hashKey对应的所有键值
*/
public Map hmGetMap(String key) {
Map map = redisTemplate.opsForHash().entries(key);
return map;
}/**
* 列表添加,单个元素添加
*
* @param k
* @param v
*/public void lPush(String k, Object v) {
ListOperations list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表取出,单个元素取出
* 使用方法时,redis会同步删除集合中的数据
* @param k
*
*/public Object lPop(String k) {
ListOperations list = redisTemplate.opsForList();
returnlist.leftPop(k);
}/**
* 列表获取
*
* @param k
* @param l
* @param l1
* @return
*/public List
4.将数据存入Redis缓存中 在service.impl下创建RedisDictInfoImpl.java
实现将数据库获取到的数据存入Redis缓存中
(数据库获取数据通过实体类和mapper即可)
package com.hikvision.isc.module.business.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hikvision.isc.common.cache.KeyConstans;
import com.hikvision.isc.common.cache.RedisUtils;
import com.hikvision.isc.module.business.entity.ibuilding.DictInfo;
import com.hikvision.isc.module.business.mapper.DictInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
/**
* 存储预警类型编码与名称的对应关系
* 存储预警类型编码与父类名称的对应关系
*/
@Service
public class RedisDictInfoImpl {@Autowired
private RedisUtils redisUtils;
@Autowired
private DictInfoMapper dictInfoMapper;
/**添加到redis中*/
public void cacheDict(){
//从数据库获取需要存入Redis缓存的数据
QueryWrapper wrapper = new QueryWrapper();
List list = dictInfoMapper.selectList(wrapper);
//遍历list,存入缓存——存储预警类型编码与名称的对应关系
list.forEach(l->{
if ("专业施工人员".equals(l.getDictName())){
l.setDictName("施工人员");
}
//调用hmSet方法将每一条对象存入存入KeyConstans.DISTKEY中
redisUtils.hmSet(KeyConstans.DISTKEY, l.getDictCode(), l.getDictName());
});
redisUtils.hmSet(KeyConstans.DISTKEY, "0", "正常");
/**
* 存储预警类型编码与父类名称的对应关系
*/
list.forEach(l1->{
if (StringUtils.isEmpty(l1.getParentCode())){
//如果父级编码为null,就将编码和编码名称存入KeyConstans.DISTPARENTKEY中
redisUtils.hmSet(KeyConstans.DISTPARENTKEY, l1.getDictCode(), l1.getDictName());
}else {
//如果父级不为空,将父级编码名称与编码名称拼接存入KeyConstans.DISTPARENTKEY中
String name = "-" + l1.getDictName();
String parentName = (String) redisUtils.hmGet(KeyConstans.DISTKEY, l1.getParentCode());
redisUtils.hmSet(KeyConstans.DISTPARENTKEY, l1.getDictCode(), parentName + name);
}
});
}}
5.创建定时任务 在business文件夹下创建init文件夹
5.1 创建定时任务管理类 在init文件夹下创建:TaskManager.java文件
使用注解:
@Component
@EnableScheduling
package com.hikvision.isc.module.business.init;
import com.hikvision.isc.module.business.service.impl.RedisDictInfoImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@EnableScheduling
public class TaskManager {
private static Logger logger = LoggerFactory.getLogger(TaskManager.class);
//注入具体实现缓存的实现类
@Autowired
private RedisDictInfoImpl redisDictInfo;
@Scheduled(cron = "自定义执行时间")
public void syncAlarmCodeAndName(){
try {
//调用具体方法将数据写入缓存
redisDictInfo.cacheDict();
}catch (Exception e){
logger.error("定时任务执行异常"+new Date(),e);
}}
}
5.2 定义定时任务启动类 在init文件夹下创建:InitTask.java,实现CommandLineRunner,重写run方法
package com.hikvision.isc.module.business.init;
import com.hikvision.isc.module.business.service.impl.RedisDictInfoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class InitTask implements CommandLineRunner {@Autowired
private TaskManager taskManager;
@Override
public void run(String... args) throws Exception {//项目启动时进行缓存
taskManager.syncAlarmCodeAndName();
}
}
6.设置启动类 在启动类上添加注解:
@EnableScheduling
7.编写测试Controller进行测试 【海星框架——Redis的使用(结合定时任务)】在business下创建controller文件夹,创建TestController.java文件
调用RedisUtils类的hmGet方法传入指定key,获取缓存中的value
package com.hikvision.isc.module.business.controller;
import com.hikvision.isc.common.cache.KeyConstans;
import com.hikvision.isc.common.cache.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags = {"测试接口"})
public class TestController {@Autowired
private RedisUtils redisUtils;
@ApiOperation("根据预警编码获取redis缓存中的预警名称")
@RequestMapping(value = "https://www.it610.com/getDictName", method = RequestMethod.GET)
public Object getDictName(@RequestParam String dictCode) {
return redisUtils.hmGet(KeyConstans.DISTKEY, dictCode);
}
}
8. 运行项目 运行项目测试:
文章图片
文章图片
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)