分布式数据存储 之 Redis(二) —— spring中的缓存抽象

时间:2022-06-04 16:23:42

分布式数据存储 之 Redis(二) —— spring中的缓存抽象

一、spring boot 中的 StringRedisTemplate

1.StringRedisTemplate Demo

第一步:引入redis依赖

最重要的依赖

compile('org.springframework.boot:spring-boot-starter-data-redis')

此依赖为springCloud 父项目 依赖(但已添加 redis 依赖)

buildscript {
ext {
springBootVersion = '2.1.2.RELEASE'
}
repositories {
mavenLocal() //maven本地仓库
maven {
url = "http://maven.aliyun.com/nexus/content/groups/public"
}
mavenCentral()//maven中心仓库
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
} subprojects {
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management' group = 'com.lichuang.kukri'
version = '1.0.0'
sourceCompatibility = 1.8 repositories {
mavenLocal() //maven本地仓库
maven {
url = "http://maven.aliyun.com/nexus/content/groups/public"
}
mavenCentral()//maven中心仓库
} ext {
springCloudVersion = 'Greenwich.RELEASE'
} dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter')
testCompile('org.springframework.boot:spring-boot-starter-test') //redis 依赖
compile('org.springframework.boot:spring-boot-starter-data-redis')
} dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
} }

第二步:创建 StringRedisTemplate 的 Bean

StringRedisTemplate 的构造函数可知需要 RedisConnectionFactory 的 Bean,又由 RedisConnectionFactory 可知需要 RedisStandaloneConfiguration 的 Bean, RedisStandaloneConfiguration 的构造函数中需要有 hostname 以及 port

@Configuration
@ComponentScan
public class AppConfig { //xxxTemplate -> 设计模式之一 模板方法设计模式 @Bean
public RedisStandaloneConfiguration redisStandaloneConfiguration(){
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("hostname",6379);
return redisStandaloneConfiguration;
} @Bean
public RedisConnectionFactory redisConnectionFactory(){
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration()); return connectionFactory;
} @Bean
public StringRedisTemplate stringRedisTemplate(){
StringRedisTemplate redisTemplate = new StringRedisTemplate(redisConnectionFactory()); return redisTemplate;
} }

第三步:获取 StringRedisTemplate 进行运用

  1. 添加数据至Redis: redisTemplate.opsForValue().set("name","test");
  2. 从Redis 获取数据: redisTemplate.opsForValue().get("name")
public class RedisServer {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); StringRedisTemplate redisTemplate = applicationContext.getBean(StringRedisTemplate.class); redisTemplate.opsForValue().set("name","test"); //System.out.println(redisTemplate.opsForValue().get("name")); /* redisTemplate.watch("name");
redisTemplate.multi();
redisTemplate.exec();*/
}
}

二、 Cache Abstraction

1.核心接口

CachManager

Spring's central cache manager SPI.

方法

​ Cache getCache(String name);

​ Collection getCacheNames();

Cache

Interface that defines common cache operations

常见实现类
  1. ConcurrentMapCache
  2. RedisCache
  3. EhCacheCache

KeyGenerator

​ SimpleKeyGenerator(默认实现类)

2. 常见注解

@Cacheable

如果缓存中有值,则使用缓存中的值;如果没有则执行业务方法并存入缓存中

属性
  1. condition

    判断

  2. unless

@CachePut

每次都会执行业务方法,并设置缓存

@CacheEvict

每次都会执行业务方法,并删除缓存

3. Cache Abstraction Demo

第一步:引入依赖

dependencies {
compile('org.springframework.boot:spring-boot-starter-data-redis')
compile group: 'org.projectlombok', name: 'lombok', version: '1.18.6'
compile group: 'com.alibaba', name: 'fastjson', version: '1.2.56'
}

第二步:创建 CacheManager 的 Bean

注:

​ 1. GenericFastJsonRedisSerializer 类 使 Value 的 储存方式 为 Josn

@Configuration
@ComponentScan
@MapperScan("com.lichuang.kukri.springcloudproject.config.dao")
@EnableCaching
public class AppConfig { //xxxTemplate -> 设计模式之一 模板方法设计模式 @Bean
public RedisStandaloneConfiguration redisStandaloneConfiguration(){
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("hostname",6379);
return redisStandaloneConfiguration;
} @Bean
public CacheManager cacheManager(){
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory()); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer())); RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,redisCacheConfiguration); return redisCacheManager;
} }

第三步:创建 Service

@Service
public class CacheService { @CachePut(cacheNames = "person")
public Person update(int age){
Person person = new Person();
person.setPersonName("admin");
person.setAge(age);
return person;
} @Cacheable(cacheNames = "person")
public Person selectP(int age){
Person person = new Person();
person.setPersonName("test");
person.setAge(age);
return person;
} @Cacheable(cacheNames = "cache")
public String selectC(int i){
System.out.println("select");
return "admin";
}
}

​ Person.java(实体类)

public class Person {

    private String personName;

    private int age;

    public String getPersonName() {
return personName;
} public void setPersonName(String personName) {
this.personName = personName;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}

第四步:运行

public class RedisServer {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); PersonDao personDao = applicationContext.getBean(PersonDao.class);
List<Person> people = personDao.select();
for (int i = 0; i < people.size(); i++) {
System.out.println(people.get(i).getPersonName() + "-" + people.get(i).getAge());
} /*CacheService cacheService = applicationContext.getBean(CacheService.class);
for (int i = 0; i < 2; i++) {
//System.out.println(cacheService.selectC(i)); cacheService.update(i);
}*/
}
}

第五步:在 Redis 中获取

127.0.0.1:6379> get cache::0
"\"admin\""
127.0.0.1:6379> get person::0
"{\"@type\":\"com.bean.Person\",\"age\":1,\"name\":\"test\"}"