说明:这里我使用的远程连接工具为Redis Desktop Manager进行的调试

最近接收了一个项目,总是在运行一天后出现异常,之后通过服务器控制台发现报错 cannot be cast to java.lang.String "" ,经过调试发现这是Redis 缓存过期导致的异常,为了解决问题我尝试从数据库中重新获取并存入Redis代码如下所示:

 public String getConfig(String key, RedisUtil redisUtil) {
String value = "";
//尝试从缓存中获取数据
String str = redisUtil.getConfig(key);
//判断获取的数据是否为空
if("".equals(str) || str.equals(null)) {
//如果为空,从数据库进行获取
value = sysConfigMapper.findByConfigKey(key);
//放入缓存
redisTemplate.opsForValue().set(key,str);
return value;
}
return str;
}

首先尝试从缓存中缓存中获取数据,判断获取的数据是否为空,如果为空说明缓存中的数据已过期,从数据库中重新获取,并放入缓存中,那么问题来了,当我尝试调用 redisTemplate.opsForValue().set(key,str);这段代码时发现总是无法将数据放入缓存中,之后我在单元测试中加入了如下代码进行测试:

package test;

import com.hn.haoniu.businesscore.common.redis.RedisUtil;
import com.hn.haoniu.businesscore.dao.SysConfigMapper;
import com.hn.haoniu.businesscore.model.database.SysConfig;
import com.hn.haoniu.rest.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.junit4.SpringRunner;
import tk.mybatis.mapper.entity.Example;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.io.*;
import java.util.concurrent.TimeUnit;


@RunWith(SpringRunner.class)
@SpringBootApplication(scanBasePackages={"com.hn.haoniu.*"})
@SpringBootTest
public class SysConfigTest {
@Autowired
public SysConfigMapper mapper;

@Autowired
private RedisUtil redisUtil;
@Autowired
public RedisTemplate redisTemplate;

@Test
public void test() throws Exception {
redisTemplate.opsForValue().set("key","5000");
}


}

发现放入成功,放入缓存成功,但是以下面的方式放入缓存并使用Redis Desktop Manager查看发现始终无法缓存成功:

String str = "5000";
redisTemplate.opsForValue().set(key,str);

之后经过身边的一个大哥提醒,直接传入的字符串"5000" 是一个常量,我就尝试在变量前加入final关键字,发现缓存成功

final String str = "5000";
redisTemplate.opsForValue().set(key,str);

但是之后想到,常量在运行期是无法修改值的,所以最后我将代码修改为如下所示:

/**
* 描述:
* 判断从Redis 获取到的值是否为空
* 如果为空测从数据库中获取并重新放入Redis缓存中
* @param key Redis的key
* @param redisUtil redis 帮助类
* @return 返回从数据库中获取的值
*/
public String getConfig(String key, RedisUtil redisUtil) {
String value = "";
String str = redisUtil.getConfig(key);
if("".equals(str) || str.equals(null)) {
value = sysConfigMapper.findByConfigKey(key);
redisTemplate.opsForValue().set(key,"dev:"+str);
return value;
}
return str;
}

最后再贴上一个连接,虽然不是同​