欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

关于SpringBoot使用Redis空指针的问题(不能成功注入的问题)

程序员文章站 2022-04-12 23:33:37
自己的一个小项目使用redis在一个类里可以注入成功,而在另一个类以却不能注入成功不多bb直接上代码package com.common.utils; import org.springframewo...

自己的一个小项目使用redis在一个类里可以注入成功,而在另一个类以却不能注入成功

不多bb直接上代码

package com.common.utils;
 
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.data.redis.core.boundlistoperations;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.stereotype.component;
import org.springframework.util.collectionutils;
 
import java.util.list;
import java.util.map;
import java.util.set;
import java.util.concurrent.timeunit;
 
 
@component
public class redisutil {
 
 @autowired
 private redistemplate<string, object> redistemplate;
 
 public redisutil(redistemplate<string, object> redistemplate) {
  this.redistemplate = redistemplate;
 }
 
 /**
  * 指定缓存失效时间
  * @param key 键
  * @param time 时间(秒)
  * @return
  */
 public boolean expire(string key,long time){
  try {
   if(time>0){
    redistemplate.expire(key, time, timeunit.seconds);
   }
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 根据key 获取过期时间
  * @param key 键 不能为null
  * @return 时间(秒) 返回0代表为永久有效
  */
 public long getexpire(string key){
  return redistemplate.getexpire(key,timeunit.seconds);
 }
 
 /**
  * 判断key是否存在
  * @param key 键
  * @return true 存在 false不存在
  */
 public boolean haskey(string key){
  try {
   return redistemplate.haskey(key);
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 删除缓存
  * @param key 可以传一个值 或多个
  */
 @suppresswarnings("unchecked")
 public void del(string ... key){
  if(key!=null&&key.length>0){
   if(key.length==1){
    redistemplate.delete(key[0]);
   }else{
    redistemplate.delete(collectionutils.arraytolist(key));
   }
  }
 }
 
 //============================string=============================
 /**
  * 普通缓存获取
  * @param key 键
  * @return 值
  */
 public object get(string key){
  return key==null?null:redistemplate.opsforvalue().get(key);
 }
 
 /**
  * 普通缓存放入
  * @param key 键
  * @param value 值
  * @return true成功 false失败
  */
 public boolean set(string key,object value) {
  try {
   redistemplate.opsforvalue().set(key, value);
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 普通缓存放入并设置时间
  * @param key 键
  * @param value 值
  * @param time 时间(分钟) time要大于0 如果time小于等于0 将设置无限期
  * @return true成功 false 失败
  */
 public boolean set(string key,object value,long time){
  try {
   if(time>0){
    redistemplate.opsforvalue().set(key, value, time, timeunit.minutes);
   }else{
    set(key, value);
   }
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 递增
  * @param key 键
  * @param delta 要增加几(大于0)
  * @return
  */
 public long incr(string key, long delta){
  if(delta<0){
   throw new runtimeexception("递增因子必须大于0");
  }
  return redistemplate.opsforvalue().increment(key, delta);
 }
 
 /**
  * 递减
  * @param key 键
  * @param delta 要减少几(小于0)
  * @return
  */
 public long decr(string key, long delta){
  if(delta<0){
   throw new runtimeexception("递减因子必须大于0");
  }
  return redistemplate.opsforvalue().increment(key, -delta);
 }
 
 //================================map=================================
 /**
  * hashget
  * @param key 键 不能为null
  * @param item 项 不能为null
  * @return 值
  */
 public object hget(string key,string item){
  return redistemplate.opsforhash().get(key, item);
 }
 
 /**
  * 获取hashkey对应的所有键值
  * @param key 键
  * @return 对应的多个键值
  */
 public map<object,object> hmget(string key){
  return redistemplate.opsforhash().entries(key);
 }
 
 /**
  * hashset
  * @param key 键
  * @param map 对应多个键值
  * @return true 成功 false 失败
  */
 public boolean hmset(string key, map<string,object> map){
  try {
   redistemplate.opsforhash().putall(key, map);
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * hashset 并设置时间
  * @param key 键
  * @param map 对应多个键值
  * @param time 时间(秒)
  * @return true成功 false失败
  */
 public boolean hmset(string key, map<string,object> map, long time){
  try {
   redistemplate.opsforhash().putall(key, map);
   if(time>0){
    expire(key, time);
   }
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 向一张hash表中放入数据,如果不存在将创建
  * @param key 键
  * @param item 项
  * @param value 值
  * @return true 成功 false失败
  */
 public boolean hset(string key,string item,object value) {
  try {
   redistemplate.opsforhash().put(key, item, value);
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 向一张hash表中放入数据,如果不存在将创建
  * @param key 键
  * @param item 项
  * @param value 值
  * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  * @return true 成功 false失败
  */
 public boolean hset(string key,string item,object value,long time) {
  try {
   redistemplate.opsforhash().put(key, item, value);
   if(time>0){
    expire(key, time);
   }
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 删除hash表中的值
  * @param key 键 不能为null
  * @param item 项 可以使多个 不能为null
  */
 public void hdel(string key, object... item){
  redistemplate.opsforhash().delete(key,item);
 }
 
 /**
  * 判断hash表中是否有该项的值
  * @param key 键 不能为null
  * @param item 项 不能为null
  * @return true 存在 false不存在
  */
 public boolean hhaskey(string key, string item){
  return redistemplate.opsforhash().haskey(key, item);
 }
 
 /**
  * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  * @param key 键
  * @param item 项
  * @param by 要增加几(大于0)
  * @return
  */
 public double hincr(string key, string item,double by){
  return redistemplate.opsforhash().increment(key, item, by);
 }
 
 /**
  * hash递减
  * @param key 键
  * @param item 项
  * @param by 要减少记(小于0)
  * @return
  */
 public double hdecr(string key, string item,double by){
  return redistemplate.opsforhash().increment(key, item,-by);
 }
 
 //============================set=============================
 /**
  * 根据key获取set中的所有值
  * @param key 键
  * @return
  */
 public set<object> sget(string key){
  try {
   return redistemplate.opsforset().members(key);
  } catch (exception e) {
   e.printstacktrace();
   return null;
  }
 }
 
 /**
  * 根据value从一个set中查询,是否存在
  * @param key 键
  * @param value 值
  * @return true 存在 false不存在
  */
 public boolean shaskey(string key,object value){
  try {
   return redistemplate.opsforset().ismember(key, value);
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 将数据放入set缓存
  * @param key 键
  * @param values 值 可以是多个
  * @return 成功个数
  */
 public long sset(string key, object...values) {
  try {
   return redistemplate.opsforset().add(key, values);
  } catch (exception e) {
   e.printstacktrace();
   return 0;
  }
 }
 
 /**
  * 将set数据放入缓存
  * @param key 键
  * @param time 时间(秒)
  * @param values 值 可以是多个
  * @return 成功个数
  */
 public long ssetandtime(string key,long time,object...values) {
  try {
   long count = redistemplate.opsforset().add(key, values);
   if(time>0) {
    expire(key, time);
   }
   return count;
  } catch (exception e) {
   e.printstacktrace();
   return 0;
  }
 }
 
 /**
  * 获取set缓存的长度
  * @param key 键
  * @return
  */
 public long sgetsetsize(string key){
  try {
   return redistemplate.opsforset().size(key);
  } catch (exception e) {
   e.printstacktrace();
   return 0;
  }
 }
 
 /**
  * 移除值为value的
  * @param key 键
  * @param values 值 可以是多个
  * @return 移除的个数
  */
 public long setremove(string key, object ...values) {
  try {
   long count = redistemplate.opsforset().remove(key, values);
   return count;
  } catch (exception e) {
   e.printstacktrace();
   return 0;
  }
 }
 //===============================list=================================
 
 /**
  * 获取list缓存的内容
  * @param key 键
  * @param start 开始
  * @param end 结束 0 到 -1代表所有值
  * @return
  */
 public list<object> lget(string key, long start, long end){
  try {
   return redistemplate.opsforlist().range(key, start, end);
  } catch (exception e) {
   e.printstacktrace();
   return null;
  }
 }
 
 /**
  * 获取list缓存的长度
  * @param key 键
  * @return
  */
 public long lgetlistsize(string key){
  try {
   return redistemplate.opsforlist().size(key);
  } catch (exception e) {
   e.printstacktrace();
   return 0;
  }
 }
 
 /**
  * 通过索引 获取list中的值
  * @param key 键
  * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  * @return
  */
 public object lgetindex(string key,long index){
  try {
   return redistemplate.opsforlist().index(key, index);
  } catch (exception e) {
   e.printstacktrace();
   return null;
  }
 }
 
 /**
  * 将list放入缓存
  * @param key 键
  * @param value 值
  * @return
  */
 public boolean lset(string key, object value) {
  try {
   redistemplate.opsforlist().rightpush(key, value);
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 将list放入缓存
  * @param key 键
  * @param value 值
  * @param time 时间(秒)
  * @return
  */
 public boolean lset(string key, object value, long time) {
  try {
   redistemplate.opsforlist().rightpush(key, value);
   if (time > 0) {
    expire(key, time);
   }
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 将list放入缓存
  * @param key 键
  * @param value 值
  * @return
  */
 public boolean lset(string key, list<object> value) {
  try {
   redistemplate.opsforlist().rightpushall(key, value);
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 将list放入缓存
  * @param key 键
  * @param value 值
  * @param time 时间(秒)
  * @return
  */
 public boolean lset(string key, list<object> value, long time) {
  try {
   redistemplate.opsforlist().rightpushall(key, value);
   if (time > 0) {
    expire(key, time);
   }
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 根据索引修改list中的某条数据
  * @param key 键
  * @param index 索引
  * @param value 值
  * @return
  */
 public boolean lupdateindex(string key, long index,object value) {
  try {
   redistemplate.opsforlist().set(key, index, value);
   return true;
  } catch (exception e) {
   e.printstacktrace();
   return false;
  }
 }
 
 /**
  * 移除n个值为value
  * @param key 键
  * @param count 移除多少个
  * @param value 值
  * @return 移除的个数
  */
 public long lremove(string key,long count,object value) {
  try {
   long remove = redistemplate.opsforlist().remove(key, count, value);
   return remove;
  } catch (exception e) {
   e.printstacktrace();
   return 0;
  }
 }
 
 /**
  * 模糊查询获取key值
  * @param pattern
  * @return
  */
 public set keys(string pattern){
  return redistemplate.keys(pattern);
 }
 
 /**
  * 使用redis的消息队列
  * @param channel
  * @param message 消息内容
  */
 public void convertandsend(string channel, object message){
  redistemplate.convertandsend(channel,message);
 }
 
 
 
 /**
  * 根据起始结束序号遍历redis中的list
  * @param listkey
  * @param start 起始序号
  * @param end 结束序号
  * @return
  */
 public list<object> rangelist(string listkey, long start, long end) {
  //绑定操作
  boundlistoperations<string, object> boundvalueoperations = redistemplate.boundlistops(listkey);
  //查询数据
  return boundvalueoperations.range(start, end);
 }
 /**
  * 弹出右边的值 --- 并且移除这个值
  * @param listkey
  */
 public object rifhtpop(string listkey){
  //绑定操作
  boundlistoperations<string, object> boundvalueoperations = redistemplate.boundlistops(listkey);
  return boundvalueoperations.rightpop();
 }
}

上面是redis的配置文件和自定义方法类,下面是调用redis自定义方法类

package com.common.config;
 
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.serializer.jackson2jsonredisserializer;
import org.springframework.data.redis.serializer.stringredisserializer;
 
 
@configuration
@enablecaching
public class redisconfig extends cachingconfigurersupport{
 /**
  * 配置自定义redistemplate
  * @return
  */
 @bean
 redistemplate<string, object> redistemplate(redisconnectionfactory redisconnectionfactory) {
 
  redistemplate<string, object> redistemplate = new redistemplate<>();
  redistemplate.setconnectionfactory(redisconnectionfactory);
  jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);
  // 设置值(value)的序列化采用jackson2jsonredisserializer。
  redistemplate.setvalueserializer(jackson2jsonredisserializer);
  // 设置键(key)的序列化采用stringredisserializer。
  redistemplate.setkeyserializer(new stringredisserializer());
  redistemplate.sethashkeyserializer(new stringredisserializer());
 
  redistemplate.afterpropertiesset();
  return redistemplate;
 }
}

上面这个是发送邮件的类,把邮箱存在redis里方便效验(不用查数据库了),性能更好一点
在这里使用@autowired和@configuration可以成功注入redis和调用其set方法
关于SpringBoot使用Redis空指针的问题(不能成功注入的问题)

且redisutil是有数据的是有数据的
但是我又新写了个业务类名为addlogintooken,添加用户登录tooken效验用的

package com.common.utils;

import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.mail.mailsendexception;
import org.springframework.mail.simplemailmessage;
import org.springframework.mail.javamail.javamailsender;

import java.util.random;

@configuration
public class setmail {

 @autowired
 redistemplate redistemplate;

 @autowired
 redisutil redisutil;

 @autowired
 private javamailsender javamailsender;

 logger logger = loggerfactory.getlogger(this.getclass());

 public string sendmail(string mail){
  string checkcode = string.valueof(new random().nextint(899999) + 100000);
  simplemailmessage message = new simplemailmessage();
  try {
   redisutil.set(mail, checkcode, 1);
   message.setfrom("742919609@qq.com");
   message.setto(mail);
   message.setsubject("欢迎成为宠物救助平台的用户");
   message.settext("您的注册验证码为:" + checkcode);

   javamailsender.send(message);
   logger.info("邮件发送成功");
  } catch (mailsendexception e) {
   logger.error("目标邮箱不存在");
  } catch (exception e) {
   e.printstacktrace();
   logger.error("文本邮件发送异常");
  }
  return checkcode;

 }
}

和那个setmail类一模一样的代码,一模一样的注释,而且都有spring的小图标,说明应该是都注入进去了呀

关于SpringBoot使用Redis空指针的问题(不能成功注入的问题)

但是调用这个却有空指针的问题:

package com.common.utils;

import com.pojo.user;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.core.redistemplate;
import java.util.date;
import java.util.uuid;

@configuration
public class addlogintooken {

 @autowired
 redistemplate redistemplate;

 @autowired
 redisutil redisutil;

 public user addloginticket(user user){

  date date = new date();
  date.settime(date.gettime()+1000*3600*30);
  user.setuser_tooken(uuid.randomuuid().tostring().replaceall("-",""));

  string user_tooken = user.getuser_tooken();
  redisutil.set("user_tooken", user_tooken);

  return user;

 }

}

debug发现redisutil为空

关于SpringBoot使用Redis空指针的问题(不能成功注入的问题)

我解决他的第一个想法是在application里加一个扫描

java.lang.nullpointerexception
	at com.common.utils.addlogintooken.addloginticket(addlogintooken.java:26)
	at com.service.impl.loginserviceimpl.login(loginserviceimpl.java:39)
	at com.controller.logincontroller.login(logincontroller.java:33)
	at sun.reflect.nativemethodaccessorimpl.invoke0(native method)
	at sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62)
	at sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43)
	at java.lang.reflect.method.invoke(method.java:498)
	at org.springframework.web.method.support.invocablehandlermethod.doinvoke(invocablehandlermethod.java:190)
	at org.springframework.web.method.support.invocablehandlermethod.invokeforrequest(invocablehandlermethod.java:138)
	at org.springframework.web.servlet.mvc.method.annotation.servletinvocablehandlermethod.invokeandhandle(servletinvocablehandlermethod.java:105)
	at org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter.invokehandlermethod(requestmappinghandleradapter.java:879)
	at org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter.handleinternal(requestmappinghandleradapter.java:793)
	at org.springframework.web.servlet.mvc.method.abstracthandlermethodadapter.handle(abstracthandlermethodadapter.java:87)
	at org.springframework.web.servlet.dispatcherservlet.dodispatch(dispatcherservlet.java:1040)
	at org.springframework.web.servlet.dispatcherservlet.doservice(dispatcherservlet.java:943)
	at org.springframework.web.servlet.frameworkservlet.processrequest(frameworkservlet.java:1006)
	at org.springframework.web.servlet.frameworkservlet.dopost(frameworkservlet.java:909)
	at javax.servlet.http.httpservlet.service(httpservlet.java:660)
	at org.springframework.web.servlet.frameworkservlet.service(frameworkservlet.java:883)
	at javax.servlet.http.httpservlet.service(httpservlet.java:741)
	at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:231)
	at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166)
	at org.apache.tomcat.websocket.server.wsfilter.dofilter(wsfilter.java:53)
	at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193)
	at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166)
	at org.springframework.web.filter.requestcontextfilter.dofilterinternal(requestcontextfilter.java:100)
	at org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:119)
	at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193)
	at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166)
	at org.springframework.web.filter.formcontentfilter.dofilterinternal(formcontentfilter.java:93)
	at org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:119)
	at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193)
	at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166)
	at org.springframework.web.filter.characterencodingfilter.dofilterinternal(characterencodingfilter.java:201)
	at org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:119)
	at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193)
	at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166)
	at org.apache.catalina.core.standardwrappervalve.invoke(standardwrappervalve.java:202)
	at org.apache.catalina.core.standardcontextvalve.invoke(standardcontextvalve.java:96)
	at org.apache.catalina.authenticator.authenticatorbase.invoke(authenticatorbase.java:541)
	at org.apache.catalina.core.standardhostvalve.invoke(standardhostvalve.java:139)
	at org.apache.catalina.valves.errorreportvalve.invoke(errorreportvalve.java:92)
	at org.apache.catalina.core.standardenginevalve.invoke(standardenginevalve.java:74)
	at org.apache.catalina.connector.coyoteadapter.service(coyoteadapter.java:343)
	at org.apache.coyote.http11.http11processor.service(http11processor.java:373)
	at org.apache.coyote.abstractprocessorlight.process(abstractprocessorlight.java:65)
	at org.apache.coyote.abstractprotocol$connectionhandler.process(abstractprotocol.java:868)
	at org.apache.tomcat.util.net.nioendpoint$socketprocessor.dorun(nioendpoint.java:1590)
	at org.apache.tomcat.util.net.socketprocessorbase.run(socketprocessorbase.java:49)
	at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1149)
	at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:624)
	at org.apache.tomcat.util.threads.taskthread$wrappingrunnable.run(taskthread.java:61)
	at java.lang.thread.run(thread.java:748)

但是还是不行,重启idea和清缓存都不行

求解

到此这篇关于关于springboot使用redis空指针的问题(不能成功注入的问题)的文章就介绍到这了,更多相关springboot使用redis空指针内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!