在项目中加入redis缓存(学习总结)

首先加入依赖

org.springframework.boot

spring-boot-starter-data-redis

org.apache.commons

commons-pool2

2.6.0

在配置文件中加入redis配置

这里要注意如果redi
s设置了密码要加上

spring.redis.password=*****

*****代表你redis设置的密码

如果链接不上

有可能是因为你的redis没开启

开启redis

输入命令查看开启redis没有

ps -ef | grep redis

如果还链接不上redis 可能是防火墙原因

输入命令关闭防火墙

systemctl stop firewalld

如果仍然链接不上

可能是redis端口未开放

去宝塔页面开放,这里就不做演示了

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

spring.jackson.time-zone=GMT+8

spring.redis.host=8.130.169.21

spring.redis.port=6379

spring.redis.database= 0

spring.redis.timeout=1800000

spring.redis.password=*****

spring.redis.lettuce.pool.max-active=20

spring.redis.lettuce.pool.max-wait=-1

#最大阻塞等待时间(负数表示没限制)

spring.redis.lettuce.pool.max-idle=5

spring.redis.lettuce.pool.min-idle=0

在config包中中加入redis的配置

package com.atguigu.yygh.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import com.fasterxml.jackson.annotation.PropertyAccessor;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.cache.CacheManager;

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.cache.interceptor.KeyGenerator;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheConfiguration;

import org.springframework.data.redis.cache.RedisCacheManager;

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.RedisSerializationContext;

import org.springframework.data.redis.serializer.RedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;

import java.time.Duration;

@Configuration

@EnableCaching

public class RedisConfig {

/**

  • 自定义key规则

  • @return

*/

@Bean

public KeyGenerator keyGenerator() {

return new KeyGenerator() {

@Override

public Object generate(Object target, Method method, Object… params) {

StringBuilder sb = new StringBuilder();

sb.append(target.getClass().getName());

sb.append(method.getName());

for (Object obj : params) {

sb.append(obj.toString());

}

return sb.toString();

}

};

}

/**

  • 设置RedisTemplate规则

  • @param redisConnectionFactory

  • @return

*/

@Bean

public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

redisTemplate.setConnectionFactory(redisConnectionFactory);

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = 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);

jackson2JsonRedisSerializer.setObjectMapper(om);

//序列号key value

redisTemplate.setKeySerializer(new StringRedisSerializer());

redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

redisTemplate.setHashKeySerializer(new StringRedisSerializer());

redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

redisTemplate.afterPropertiesSet();

return redisTemplate;

}

/**

  • 设置CacheManager缓存规则

  • @param factory

  • @return

*/

@Bean

public CacheManager cacheManager(RedisConnectionFactory factory) {

RedisSerializer redisSerializer = new StringRedisSerializer();

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);

// 配置序列化(解决乱码的问题),过期时间600秒

RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()

.entryTtl(Duration.ofSeconds(600))

.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))

.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))

.disableCachingNullValues();

RedisCacheManager cacheManager = RedisCacheManager.builder(factory)

.cacheDefaults(config)

.build();

return cacheManager;

}

}

在service层中配置要缓存的数据

package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;

import com.atguigu.yygh.cmn.listener.DictListener;

import com.atguigu.yygh.cmn.mapper.DictMapper;

import com.atguigu.yygh.cmn.service.DictService;

import com.atguigu.yygh.model.cmn.Dict;

import com.atguigu.yygh.vo.cmn.DictEeVo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.BeanUtils;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Component;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.List;

@Component

public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

@CacheEvict(value = “dict”, allEntries=true)

@Override

public void importData(MultipartFile file) {

try {

EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();

} catch (IOException e) {

e.printStackTrace();

}

}

@Cacheable(value = “dict”,keyGenerator = “keyGenerator”)

@Override

public List findChildData(Long id) {

QueryWrapper wrapper=new QueryWrapper<>();

wrapper.eq(“parent_id”,id);

List dictList = baseMapper.selectList(wrapper);

for (Dict dict : dictList) {

Long dictId = dict.getId();

boolean isChild = this.isChild(dictId);

dict.setHasChildren(isChild);

}

return dictList;

}

@Override

public void exportData(HttpServletResponse response) {

try {

response.setContentType(“application/vnd.ms-excel”);

response.setCharacterEncoding(“utf-8”);

// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系

String fileName = URLEncoder.encode(“数据字典”, “UTF-8”);

response.setHeader(“Content-disposition”, “attachment;filename=”+ fileName + “.xlsx”);

List dictList = baseMapper.selectList(null);

List dictVoList = new ArrayList<>(dictList.size());

for(Dict dict : dictList) {

DictEeVo dictVo = new DictEeVo();

BeanUtils.copyProperties(dict, dictVo, DictEeVo.class);

dictVoList.add(dictVo);

}

EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet(“数据字典”).doWrite(dictVoList);

} catch (IOException e) {

e.printStackTrace();

}

}

//判断ID下面是否有子节点

public boolean isChild(Long id){

QueryWrapper wrapper=new QueryWrapper<>();

wrapper.eq(“parent_id”,id);
Integer count = baseMapper.selectCount(wrapper);
return count>0;
}
}

最后

小编这些年深知大多数初中级工程师,想要提升自己,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此我收集整理了一份《2024年Java全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你需要这些资料,⬅专栏获取
QueryWrapper wrapper=new QueryWrapper<>();

wrapper.eq(“parent_id”,id);
Integer count = baseMapper.selectCount(wrapper);
return count>0;
}
}

最后

小编这些年深知大多数初中级工程师,想要提升自己,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此我收集整理了一份《2024年Java全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-3Fym6Ekz-1719681359734)]

[外链图片转存中…(img-W6juRZvy-1719681359734)]

[外链图片转存中…(img-qgWjrJnr-1719681359735)]

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你需要这些资料,⬅专栏获取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值