在SpringCloud项目中写了一个redis存储的工具类,使用时总是报空指针错误:
--- [nio-8001-exec-3] c.t.d.c.utils.exception.ExceptionUtil : java.lang.NullPointerException
at com.tfjybj.dtc.crawl.util.CrawlProgressUtil.<init>(CrawlProgressUtil.java:34)
原代码如下:
public class CrawlProgressUtil {
@Resource
private RedisTemplate redisTemplate;
//redis 命名规范 项目名称+服务名称+类名+自定义名
private static String redis_key = "DTC:CRAWL:BlogServiceImpl" +
":crawlBlogInfo:";
HashMap<String, Object> crawlProgressMap = new HashMap<>(2);
public CrawlProgressUtil() {
// 将redis默认的序列化方式改为String序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
}
public void nowCrwalProgress(Integer now, Integer all, String taskName) {
//将当前爬取进度存到redis
crawlProgressMap.put("currentProgress", now);
crawlProgressMap.put("allProgress", all);
redisTemplate.opsForHash().putAll(redis_key + taskName,
crawlProgressMap);
}
}
经过调试发现是RedisTemplate注入的问题,语法上没发现错误,也不是注入方式的问题,上网搜索发现原来RedisTemplate的注入得分情况:Spring注入和非Spring注入,我这个工具类在Spring之外,属于非Spring注入(可简单理解为没在Service层注入),但非Spring注入不是用@Resource这种方式,应该写配置。查了查非Spring注入的方式,觉得代码有点多,我也不太理解,就改造了一下这个工具类,让RedisTemplate在Service层注入,将注入的redisTemplate通过传参的方式传入工具类中,一下为改正后的代码:
public class CrawlProgressUtil {
//redis 命名规范 项目名称+服务名称+类名+自定义名
private static String redis_key = "DTC:CRAWL:BlogServiceImpl" +
":crawlBlogInfo:";
private RedisTemplate redisTemplate;
HashMap<String, Object> crawlProgressMap = new HashMap<>(2);
public CrawlProgressUtil(RedisTemplate redisTemplate) {
// 将redis默认的序列化方式改为String序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
this.redisTemplate = redisTemplate;
}
public void nowCrwalProgress(Integer now, Integer all, String taskName) {
//将当前爬取进度存到redis
crawlProgressMap.put("currentProgress", now);
crawlProgressMap.put("allProgress", all);
redisTemplate.opsForHash().putAll(redis_key + taskName,
crawlProgressMap);
}
}
使用方式:
在Service层实现类中注入:
@Service
public class CSDNCommentServiceImpl implements CSDNCommentService {
@Resource
private RedisTemplate redisTemplate;
//爬取的业务类
//后边代码略
}
在需要存redis的位置实例化工具类并传参:
CrawlProgressUtil cpu = new CrawlProgressUtil(redisTemplate);