pom.xml 中添加 Redis 依赖
org.springframework.boot
spring-boot-starter-data-redis
/**
* @Description: redis工具类
* @Date: 2018/12/3 17:05
* @Author: lxz
*/
@Component
public class RedisComponent {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public boolean hasKey(String key) {
return this.stringRedisTemplate.hasKey(key);
}
/**
* 实现命令:TTL key,以秒为单位,返回给定 key的剩余生存时间(TTL, time to live)。
*
* @param key
* @return
*/
public long ttl(String key) {
return stringRedisTemplate.getExpire(key);
}
/**
* 实现命令:expire 设置过期时间,单位秒
*
* @param key
* @return
*/
public void expire(String key, long timeout) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:INCR key,增加key一次
*
* @param key
* @return
*/
public long incr(String key, long delta) {
return stringRedisTemplate.opsForValue().increment(key, delta);
}
/**
* 实现命令:KEYS pattern,查找所有符合给定模式 pattern的 key
*/
public Set keys(String pattern) {
return stringRedisTemplate.keys(pattern);
}
/**
* 实现命令:DEL key,删除一个key
*
* @param key
*/
public void del(String key) {
stringRedisTemplate.delete(key);
}
// String(字符串)
/**
* 实现命令:SET key value,设置一个key-value(将字符串值 value关联到 key)
*
* @param key
* @param value
*/
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
/**
* 实现命令:SET key value EX seconds,设置key-value和超时时间(秒)
*
* @param key
* @param value
* @param timeout (以秒为单位)
*/
public void set(String key, String value, long timeout) {
stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:GET key,返回 key所关联的字符串值。
*
* @param key
* @return value
*/
public String get(String key) {
return (String)stringRedisTemplate.opsForValue().get(key);
}
// Hash(哈希表)
/**
* 实现命令:HSET key field value,将哈希表 key中的域 field的值设为 value
*
* @param key
* @param field
* @param value
*/
public void hset(String key, String field, Object value) {
stringRedisTemplate.opsForHash().put(key, field, value);
}
/**
* 实现命令:HGET key field,返回哈希表 key中给定域 field的值
*
* @param key
* @param field
* @return
*/
public String hget(String key, String field) {
return (String)stringRedisTemplate.opsForHash().get(key, field);
}
/**
* 实现命令:HDEL key field [field ...],删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
*
* @param key
* @param fields
*/
public void hdel(String key, Object... fields) {
stringRedisTemplate.opsForHash().delete(key, fields);
}
/**
* 实现命令:HGETALL key,返回哈希表 key中,所有的域和值。
*
* @param key
* @return
*/
public Map
@Autowired
private RedisComponent redisComponent;
@RequestMapping("/test")
public void test() {
redisComponent.set("stringRedisTemplate-key", "stringRedisTemplate-value");
}
/**
* @Description: 数据存储的实体类
* @Date: 2018/12/3 18:01
* @Author: lxz
*/
@RedisHash("persons")
public class Person implements Serializable {
@Id
private Long id;
private String firstName;
private String lastName;
// 注意,配置了初始化序列号记得实体类中增加无参构造,否则会报错: springdataredis Could not read JSON: Cannot construct instance of...
public Person() {}
public Person(Long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Person{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}';
}
}
/**
* @Description: Repository 接口
* @Date: 2018/12/3 18:04
* @Author: lxz
*/
public interface PersonRepository extends CrudRepository {}
@RequestMapping("/test")
public void test() {
Person person1 = new Person((long)1, "罗 ", "小小");
Person person2 = new Person((long)2, "罗 ", "大大");
Person person3 = new Person((long)3, "罗 ", "超大");
personRepository.save(person1);
// 注意,保存到 Redis 中会变成两部分,一部分是一个set,里面存储的是所有数据的 ID值
Object o1 = personRepository.findById(person1.getId()).get();
// 设置过期时间。注意,设置set不会影响到下面hash值
redisComponent.expire("persons", 20);
System.out.println(o1.toString());
List personList = new ArrayList<>();
personList.add(person1);
personList.add(person2);
personList.add(person3);
personRepository.saveAll(personList);
// 设置过期时间,设置Id为1的过期时间
redisComponent.expire("persons:1", 20);
Object o2 = personRepository.findById(person2.getId()).get();
System.out.println(o2.toString());
long count = personRepository.count();
System.out.println(count);
List idList = new ArrayList<>();
idList.add((long)1);
idList.add((long)3);
personRepository.findAllById(idList).forEach(System.out::println);
}
@SpringBootApplication
@EnableCaching
public class MyFamilyCacheApplication {
public static void main(String[] args) {
SpringApplication.run(MyFamilyCacheApplication.class, args);
}
}
/*****
* @Description: redis配置文件【注意】配置了初始化序列号记得实体类中增加无参构造,否则会报错: springdataredis Could not read JSON: Cannot construct
* instance of...
* @Date: 2018/12/3 17:08
* @Author: lxz
*/
@Configuration
public class MyRedisConfig extends CachingConfigurerSupport {
private Logger logger = LoggerFactory.getLogger(MyRedisConfig.class);
/**
* @Description 初始化redisTemplate,设置默认的序列化方式为 Json
* @Params [redisConnectionFactory]
* @Return
* @CreateTime 2018/12/5
* @Author lxz
*/
@Bean(name = "redisTemplate")
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(keySerializer());
redisTemplate.setHashKeySerializer(keySerializer());
redisTemplate.setValueSerializer(valueSerializer());
redisTemplate.setHashValueSerializer(valueSerializer());
return redisTemplate;
}
/**
* @Description 初始化cacheManager,设置默认的序列化方式为 Json;缓存的默认超时时间
* @Params [redisConnectionFactory]
* @Return
* @CreateTime 2018/12/5
* @Author lxz
*/
@Primary
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 缓存配置对象
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) // 设置缓存的默认超时时间:30分钟
.disableCachingNullValues() // 如果是空值,不缓存
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) // 设置key序列化器
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); // 设置value序列化器
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
private RedisSerializer keySerializer() {
return new StringRedisSerializer();
}
private RedisSerializer
/**
* @Description: spring Cache 缓存数据
* @Date: 2018/12/4 16:56
* @Author: lxz
*/
@Repository
@CacheConfig(cacheNames = "person")
public class PersonDao {
//使用MyRedisConfig中配置的key
//@Cacheable(value = "get", keyGenerator = "keyGenerator")
@Cacheable(value = "get", key = "'key-' + #randomInt")
public Person get(int randomInt) {
Person person = new Person((long)randomInt, "我是姓" + randomInt, "我是名" + randomInt);
return person;
}
}
@Autowired
private PersonDao personDao;
public void test() {
int randomInt = new Random().nextInt(10);
personDao.get(randomInt);
Person person = personDao.get(randomInt);
System.out.println(person.toString());
}