通用缓存key的作用
当项目中的模块越来越多的时候,需要存的缓存也越来越多,比如商品Id,订单Id,用户id等,此时若是id出现重复,将给系统带来错误。
方法:利用一个前缀来规定不同模块的缓存的key,这样不同模块之间就不会重复。
通用缓存key采用模板模式:接口->抽象类->实现类
1. 接口
1 2 3 4 5 6 7
| public interface KeyPrefix { public int expireSeconds(); public String getPrefix();
}
|
2. 抽象类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public abstract class BasePrefix implements KeyPrefix{
private int expireSeconds; private String prefix; public BasePrefix(String prefix) { this(0, prefix);
} public BasePrefix( int expireSeconds, String prefix) { this.expireSeconds = expireSeconds; this.prefix = prefix; }
public int expireSeconds() {
return expireSeconds; } public String getPrefix() { String className = getClass().getSimpleName(); return className+":" + prefix; } }
|
3. 实现类
1 2 3 4 5 6 7 8 9
| public class MiaoshaKey extends BasePrefix{ public MiaoshaKey(String prefix) { super(prefix); } public static MiaoshaKey isGoodsOver = new MiaoshaKey("go");
}
|