场景:在完成后端服务拦截器中识别token的时候,redisTemplate注入失败,redisTemplate为null。
最终采取的解决办法:
这是设置的redisTemplate的配置。
package com.tsxy.etc.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@Slf4j
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<String, String>();
//未添加@Configuration注解,导致@Bean之间相互调用出错
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
}
解决办法就是,编写一个redisBean用来生成模板,用来初始化模板:
package com.tsxy.etc.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* 初始化生成一个redisTemplate.
* 从而解决引入redisTemplate为null的情况
*/
@Component
@Slf4j
public class RedisBean {
@Autowired
private RedisTemplate redisTemplate;
public static RedisTemplate redis;
/**
*PostConstruct在构造函数之后执行,init()方法之前执行。
* 通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序
* Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
*/
@PostConstruct
public void getRedisTemplate() {
redis = this.redisTemplate;
log.info("初始化-------redisTemplate----");
}
}
应用:
//使用token去redis的中查看是否有
RedisTemplate redisTemplate = RedisBean.redis;
Object value = redisTemplate.opsForValue().get(token);
System.out.println(value);
//给token续命
redisTemplate.expire(token, Duration.ofDays(Constants.TOKEN_TIME));
if (Objects.isNull(value)) {
//redis中的token为空,拦截
response.setStatus(401);
String jsonString = JSONObject.toJSONString(res);
response.getWriter().write(jsonString);
return false;
}
当@Autowired声明redisTemplate失效的时候,可以采用这种方式。