?????? 现实中,本地环境(dev)和开发环境(feature)会共同使用相同的中间件(本篇拿Redis举例),对于不同环境中的,图片、视频、语音等资源类型的预览地址url,需要配置不同的ip和port地址;如何优美的解决它?
项目中添加下方类CacheKeyGenerator:
import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class CacheKeyGenerator implements KeyGenerator {
@Value("${spring.profiles.active}")
private String profilesActive;
@Override
public Object generate(Object target, Method method, Object... params) {
Long id = (Long) params[0];
String cacheKey = new StringBuilder(profilesActive).append("_").append(id).toString();
log.info("[cacheKeyGenerate],cacheKey={}", cacheKey);
return cacheKey;
}
}
在需要缓存的Service方法上添加@Cacheable注解:
@Cacheable(cacheNames = CacheNames.DETAIL, keyGenerator = "cacheKeyGenerator")
public XXXXVo queryById(Long id){
XXXX;
return vo;
}
//请原谅不能贴源码出来;
redis下存储最终效果: