函数式接口:有且仅有一个抽象方法
@EnableCaching//开启缓存
package com.kaikeba.jspdemo.service; import com.kaikeba.jspdemo.dao.UserDao; import com.kaikeba.jspdemo.bean.User; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.redis.core.BoundValueOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.naming.ldap.Rdn; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.TimeUnit; @Service public class UserServiceImpl implements UserService { @Autowired public UserDao userDao; @Autowired private RedisTemplate<Object, Object> redisTemplate; @CacheEvict(value = "realTimeCache", allEntries = true) @Override public void sava(User employee) { userDao.insertUser(employee); } /* @Cacheable(value = "realTimeCache", key = "'user_'+#id")*/ @Override public User findOne(int id) { return userDao.findUserById(id); } //使用双重检测锁 @Override public Integer findUserCount() { //获取redis操作对象 BoundValueOperations<Object, Object> ops = redisTemplate.boundValueOps("count"); Object count = ops.get(); //双重检测锁主要 if (count == null) { synchronized (this) { count = ops.get(); if (count == null) { count = userDao.findCount(); DateTimeFormatter s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss"); System.out.println(LocalDateTime.now().format(s)+"d"+userDao.findCount() + "dddddd"); //将查询的数据写入到redis中,并设置到期时效 ops.set(count, 10, TimeUnit.SECONDS); } } } //从缓存中读取数据 return (Integer) count; } }
自动生成key值
package com.kaikeba.jspdemo.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Configuration;
/**
* @author liwenjie
* @date 2019-06-15 14:23
* @mail wenjieli@newbanker.cn
*/
@Configuration
public class RedisCache extends CachingConfigurerSupport {
@Override
public KeyGenerator keyGenerator() {
return (taget, method, param) -> {
String tagetName = taget.getClass().getName();
String methodName = method.getName();
return tagetName + "_" + methodName + "_" + param[0].toString();
};
}
}