package com.oracle.ssm.shop.cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;
import java.io.Serializable;
import java.util.concurrent.Callable;
import java.util.concurrent.locks.ReadWriteLock;
@Component
public class RedisCache implements Cache {
@Autowired
private RedisTemplate redisTemplate;
//缓存的名字 该缓存类的唯一标识
private String name;
/**
* @Description: 清空缓存
* @Author: Administrator
* @Param: []
* @Return void
**/
@Override
public void clear() {
System.out.println("-------clear cache-----");
redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "ok";
}
});
}
/**
* @Description: 删除缓存
* @Author: Administrator
* @Param: [key]
* @Return void
**/
@Override
public void evict(Object key) {
System.out.println("-------remove cache------");
final String keyf=key.toString();
redisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
return connection.del(keyf.getBytes());
}
});
}
/**
* @Description: 命中缓存 取缓存
* @Author: Administrator
* @Param: [key]
* @Return org.springframework.cache.Cache.ValueWrapper
**/
@Override
public ValueWrapper get(Object key) {
System.out.println("------get cache-------"+key.toString());
final String keyf = key.toString();
Object object = null;
object = redisTemplate.execute(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
byte[] key = keyf.getBytes();
byte[] value = connection.get(key);
if (value == null) {
System.out.println("------hit no cache-------");
return null;
}
return
缓存类实现Cache接口
最新推荐文章于 2022-07-29 22:07:27 发布