最近在项目中(spring)集成 redis 时,在去工厂实例时,一直抱空指针 异常:
但是单元测试始终正常:
以下为 redis-config.xml 文件
<context:property-placeholder location="classpath:properties/redis.properties" ignore-unresolvable="true"/>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxTotal}"/>
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxWaitMillis" value="${redis.maxWait}"/>
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
</bean>
<!-- 单例模式 默认 -->
<bean id="connectionFactory" class="redis.clients.jedis.JedisPool">
<constructor-arg ref="jedisPoolConfig" name="poolConfig"/>
<constructor-arg name="host" value="${redis.host}"/>
<constructor-arg name="port" value="${redis.port}"/>
<constructor-arg name="timeout" value="${redis.timeout}"/>
</bean>
测试代码:
@Test
public void redisTest(){
Jedis jedis=jedisConnectionFactory.getResource();
jedis.set("123","312312");
System.out.println(jedis.get("123"));
}
测试运行结果为:
312312
但是在 mybatis
中加入二级缓存抱错
xxxMapper.xml
```xml
<cache type="extra.cache.RedisCache"/>
```
二级缓存接口继承处理...
@Component
public class RedisCache implements Cache {
private static final Logger logger= LoggerFactory.getLogger(RedisCache.class);
@Autowired
private JedisPool jedisConnectionFactory;
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final String id;
public RedisCache(final String id){
if(id==null){
throw new IllegalArgumentException("Cache instances require an ID");
}
logger.debug("MybatisRedisCache:id=" + id);
this.id=id;
}
/**
* 获取 id
* @return
*/
public String getId() {
return this.id;
}
/**
* 存储数据到 redis 数据库中
* @param key
* @param value
*/
public void putObject(Object key, Object value) {
logger.info("putObject :"+key+"= "+value);
Jedis connection= jedisConnectionFactory.getResource();
RedisSerializer<Object> serializer=new JdkSerializationRedisSerializer();
connection.set(serializer.serialize(key),serializer.serialize(value));
connection.close();
}
/**
* 从 redis 中获取 数据
* @param key
* @return
*/
public Object getObject(Object key) {
logger.info("jedisConnectionFactory : "+jedisConnectionFactory);
Jedis connection= jedisConnectionFactory.getResource();
RedisSerializer<Object> serializer=new JdkSerializationRedisSerializer();
Object result=serializer.deserialize(connection.get(serializer.serialize(key)));
connection.close();
return result;
}
报的错误如下:打印日志说明为 空对象(JedisPool)
INFO extra.cache.RedisCache - jedisConnectionFactory : null
Error querying database. Cause: java.lang.NullPointerException
### Cause: java.lang.NullPointerException
-
初步怀疑为spring 加载顺序的问题,但是采用 SpringContextUtil.getBean("") ,依旧获取不了 该实例
public class SpringContextUtil implements ApplicationContextAware{...}
- 该项目采用多maven结构,同时子maven 打包时,存在一系列问题... 导致子模块之间没有通信
文件没有引入进去,
不能直接在 web.xml 直接配置(解决方案是 import 引入)
具体原因,还待研究;