1、pom.xml导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.yml配置文件中配置Redis数据源
redis:
host:
password:
port:
database: 7
jedis:
pool:
max-idle: 10
max-active: 10
min-idle: 4
3.把实体对象存放进Redis。
我是在项目初始化完成后将热点数据存入Redis,然后在不同场景去调用。
ServletContextListener接口能够监听 ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期。当servlet容器启动或者终止web应用时,会触发ServletContextEvent 事件。该事件由ServletContextListener 来处理。在 ServletContextListener 接口中定义了处理ServletContextEvent 事件的两个方法。
另外一点就是,由于Redis不支持对象的存放,需要将对象序列化或者 转成json。我自己用的是转成json的方式,简单、方便,直接引入包就可以直接使用,不需要额外代码。
/**
* @ClassNameInitServletContextListener
* @Description TODO
* @Author Yuyan
* @Date 2020/8/1815:07
* @Version V1.0
*/
@WebListener
@RestController
@RequestMapping("/redis")
public class InitServletContextListener implements ServletContextListener {
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private ListFieldService listFieldService;
public void initService(ServletContextEvent servletContextEvent){
WebApplicationContext wat = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());
listFieldService=wat.getBean(ListFieldService.class);
}
@SneakyThrows
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
List<Form> formList = listFieldService.getAllField();
for (Form form:formList) {
redisTemplate.opsForValue().set("form:"+form.getFormId().toString(),new ObjectMapper().writeValueAsString(form) );
}
List<CustomForm> customFormList = listFieldService.getAllCustomForm();
for (CustomForm customForm:customFormList) {
String keyString = customForm.getUserEid()+"-"+customForm.getFormId().toString();
redisTemplate.opsForValue().set("column:"+keyString, new ObjectMapper().writeValueAsString(customForm));
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("系统销毁。。。");
}
4.从Redis中获取数据
public Object getListFieldConfig(String userEid, String formId) throws JsonProcessingException {
ObjectMapper om = new ObjectMapper();
CustomForm customForm = new CustomForm();
String key = "column:"+userEid+"-"+formId;
// CustomForm customForm = (CustomForm) redisTemplate.opsForValue().get(key);
String customForm_1 = redisTemplate.opsForValue().get(key);
customForm = om.readValue(customForm_1, CustomForm.class);
if(null == customForm){
customForm = customFieldMapper.findCustomField(userEid, formId);
}
if(null != customForm){
return customForm;
}else{
Form form = new Form();
String fKey = "form:"+formId;
String form_1 = redisTemplate.opsForValue().get(fKey);
form = om.readValue(form_1, Form.class);
if(null == form){
form = customFieldMapper.findFormById(formId);
}
return form;
}
}