分布式数据存储 之 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\"}"

分布式数据存储 之 Redis(二) —— spring中的缓存抽象的更多相关文章

  1. 分布式数据存储 之 Redis(一) —— 初识Redis

    分布式数据存储 之 Redis(一) -- 初识Redis 为什么要学习并运用Redis?Redis有什么好处?我们步入Redis的海洋,初识Redis. 一.Redis是什么 ​ Redis 是一个 ...

  2. 使用Spring提供的缓存抽象机制整合EHCache为项目提供二级缓存

      Spring自身并没有实现缓存解决方案,但是对缓存管理功能提供了声明式的支持,能够与多种流行的缓存实现进行集成. Spring Cache是作用在方法上的(不能理解为只注解在方法上),其核心思想是 ...

  3. redis在spring中的配置及java代码实现

    1.建一个redis.properties属性文件 # Redis Setting redis.addr = 127.0.0.1 redis.port = 6379 redis.auth = mast ...

  4. Redis整合Spring结合使用缓存实例

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文介绍了如何在Spring中配置redis,并通过Spring中AOP的思想,将缓存的 ...

  5. Redis整合Spring结合使用缓存实例(转)

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文介绍了如何在Spring中配置redis,并通过Spring中AOP的思想,将缓存的 ...

  6. spring中使用缓存

    一.启用对缓存的支持 Spring 对缓存的支持最简单的方式就是在方法上添加@Cacheable和@CacheEvict注解, 再添加注解之前,必须先启用spring对注解驱动的支持,基于java的配 ...

  7. Redis学习总结(3)——Redis整合Spring结合使用缓存实例

    摘要:本文介绍了如何在Spring中配置redis,并通过Spring中AOP的思想,将缓存的方法切入到有需要进入缓存的类或方法前面. 一.Redis介绍 什么是Redis? redis是一个key- ...

  8. Redis整合Spring结合使用缓存实例(三)

    一.Redis介绍 什么是Redis? redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set( ...

  9. 使用Redis在Hibernate中进行缓存

    Hibernate是Java编程语言的开放源代码,对象/关系映射框架.Hibernate的目标是帮助开发人员摆脱许多繁琐的手动数据处理任务.Hibernate能够在Java类和数据库表之间以及Java ...

随机推荐

  1. [树套树]K大数查询

    有N个位置,M个操作.操作有两种,每次操作如果是1 a b c的形式表示在第a个位置到第b个位置,每个位置加入一个数c如果是2 a b c形式,表示询问从第a个位置到第b个位置,第C大的数是多少.为了 ...

  2. POJ2243 Knight Moves —— A*算法

    题目链接:http://poj.org/problem?id=2243 Knight Moves Time Limit: 1000MS   Memory Limit: 65536K Total Sub ...

  3. iOS自定义提示弹出框(类似UIAlertView)

    菜鸟一枚,大神勿喷.自己在牛刀小试的时候,发现系统的UIAlertView有点不喜欢,然后就自己自定义了一个UIAlertView,基本上实现了系统的UIAlertView,可以根据项目的需求修改UI ...

  4. topcoder 的一些输入输出格式

    自从上年的11月份参加过TC的比赛后,就再也没有参加了,因为它的输入输出格式比较难接受,还有它的页面字体比较小,看得我很辛苦...藉口藉口--懒而已!不过以后我会尽量去参加的,为了提高自己的编程能力. ...

  5. 使用PHP对word文档进行操作的方法

    使用php时,因为加密等原因,如果直接用FILE后者OPEN等函数读取WORD的话往往是乱码,原来要使用COM 这是我简单的一个读取并存储到新的WORD上的文件<? // 建立一个指向新COM组 ...

  6. 一步一步学Silverlight 2系列(17):数据与通信之ADO.NET Data Services

    概述 Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, ...

  7. NSString -- UILabel中字体有多种颜色,字符串自动计算高度/换行

    一:UILabel中字体有多种颜色 UILabel *label = [[UILabel alloc] init]; label.frame = CGRectMake(, , , ); label.b ...

  8. Unable to instantiate receiver XXXXXX

    运行一个工程的时候时logcat中出现了“Unable to instantiate receiver XX..”. 检查后发现,由于是东拼西凑的代码,所以在Manifest文件里注册了Receive ...

  9. 小K的农场(差分约束)

    题目大意 n个点 m条描述 农场 a 比农场 b 至少多种植了 c 个单位的作物. 农场 a 比农场 b 至多多种植了 c 个单位的作物. 农场 a 与农场 b 种植的作物数一样多. 题解 差分约束裸 ...

  10. Android适合组件化开发的路由框架:Launch

    1.概述 最近越来越不想写代码了,特别是一些重复性的代码,比如由于每次启动一个 Activity,我们都会很习惯的在 Activity 中写下: public static void launch(A ...