定义一个全局变量,并在 Application 启动时使用 ApplicationContextAware 接口初始化。
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* RedisTemplateService
*
* @author Andy
* @date 2023/2/11
*/
@Component
public class RedisTemplateService implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Qualifier("redisTemplate")
private static RedisTemplate redisTemplate;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (RedisTemplateService.applicationContext == null) {
RedisTemplateService.applicationContext = applicationContext;
}
redisTemplate = (RedisTemplate) applicationContext.getBean("redisTemplate");
}
public static RedisTemplate getRedisTemplate() {
return redisTemplate;
}
}
在静态工具类中,通过 RedisTemplateUtil 获取 RedisTemplate。
import com.cbwx.mall.common.security.service.RedisTemplateService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Component;
/**
* 缓存工具
*
* @author Andy
* @date 2023/2/10
*/
@Component
public class RedisTemplateUtil {
public static Object get(String key) {
return RedisTemplateService.getRedisTemplate().opsForValue().get(key);
}
public static Object get(String key, String partKey) {
HashOperations hashOperations = RedisTemplateService.getRedisTemplate().opsForHash();
return hashOperations.get(key, partKey);
}
}
在工作中实战化一种解决方案,希望对你有所帮助。