spring cache使用redis

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: spring cache使用redis

乐观意味着不对无可奈何的事情怨天尤人。怨天尤人是那些失去自我信赖的人的接口——雷音

首先引入redisjson依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-json</artifactId>
</dependency>

然后进行配置

package com.ruben.simplecache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@EnableCaching
@SpringBootApplication
public class SimpleCacheApplication {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        final RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
        final RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return new RedisCacheManager(redisCacheWriter, cacheConfig);
    }
    public static void main(String[] args) {
        SpringApplication.run(SimpleCacheApplication.class, args);
    }
}

别忘了给我们的实体类无参构造器

package com.ruben.simplecache;
public class Book {
    private String isbn;
    private String title;
    public Book() {
    }
    public Book(String isbn, String title) {
        this.isbn = isbn;
        this.title = title;
    }
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Override
    public String toString() {
        return "Book{" + "isbn='" + isbn + '\'' + ", title='" + title + '\'' + '}';
    }
}

运行AppRunner

package com.ruben.simplecache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(AppRunner.class);
    private final BookRepository bookRepository;
    public AppRunner(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
    @Override
    public void run(String... args) throws Exception {
        logger.info(".... Fetching books");
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info(".... Updating books");
        logger.info("isbn-1234 -->" + bookRepository.updateByIsbn(new Book("isbn-1234", "Some book")));
        logger.info("isbn-4567 -->" + bookRepository.updateByIsbn(new Book("isbn-4567", "Some book")));
        logger.info(".... Fetching books");
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
        logger.info("... Removing Books");
        logger.info("isbn-1234 -->" + bookRepository.removeByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.removeByIsbn("isbn-4567"));
        logger.info(".... Fetching books");
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
    }
}

我们的持久层SimpleBookRepository代码和AppRunner一样,都不需要变动

package com.ruben.simplecache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class SimpleBookRepository implements BookRepository {
    private static final Logger log = LoggerFactory.getLogger(SimpleBookRepository.class);
    @Override
    @Cacheable("books")
    public Book getByIsbn(String isbn) {
        simulateSlowService();
        log.warn("getByIsbn called {}", isbn);
        return new Book(isbn, "Some book");
    }
    @Override
    @CacheEvict("books")
    public Book removeByIsbn(String isbn) {
        log.warn("removeByIsbn called {}", isbn);
        simulateSlowService();
        return new Book(isbn, "Some book");
    }
    @Override
    @CachePut("books")
    public Book updateByIsbn(Book book) {
        log.warn("updateByIsbn called {}", book);
        simulateSlowService();
        return book;
    }
    // Don't do this at home
    private void simulateSlowService() {
        try {
            long time = 3000L;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}

运行结果:

可以看到其是使用注解上的value以及参数作为缓存的key,所以我们updateByIsBn需要改为用String isbn作为参数

该方法将由原本的根据IsBn更新,改为从数据库中查询数据,同步到缓存

@Override
@CachePut("books")
public Book updateByIsbn(String isbn) {
    final Book book = new Book(isbn, "Some book");
    log.warn("updateByIsbn called {}", book);
    simulateSlowService();
    return book;
}

修改AppRunner后再次运行

package com.ruben.simplecache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(AppRunner.class);
    private final BookRepository bookRepository;
    public AppRunner(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
    @Override
    public void run(String... args) throws Exception {
        logger.info(".... Fetching books");
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info(".... Updating books");
        logger.info("isbn-1234 -->" + bookRepository.updateByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.updateByIsbn("isbn-4567"));
        logger.info(".... Fetching books");
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
        logger.info("... Removing Books");
        logger.info("isbn-1234 -->" + bookRepository.removeByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.removeByIsbn("isbn-4567"));
        logger.info(".... Fetching books");
        logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
        logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
    }
}

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
27天前
|
NoSQL Java 测试技术
字节二面:Spring Boot Redis 可重入分布式锁实现原理?
字节二面:Spring Boot Redis 可重入分布式锁实现原理?
117 0
|
22天前
|
消息中间件 NoSQL Java
Redis Streams在Spring Boot中的应用:构建可靠的消息队列解决方案【redis实战 二】
Redis Streams在Spring Boot中的应用:构建可靠的消息队列解决方案【redis实战 二】
43 1
|
5天前
|
NoSQL Java Redis
Spring boot 实现监听 Redis key 失效事件
【2月更文挑战第2天】 Spring boot 实现监听 Redis key 失效事件
28 0
|
22天前
|
存储 NoSQL 关系型数据库
轻松打卡:使用Spring Boot和Redis Bitmap构建高效签到系统【redis实战 四】
轻松打卡:使用Spring Boot和Redis Bitmap构建高效签到系统【redis实战 四】
33 0
|
22天前
|
NoSQL Java Redis
Spring Boot和Redis Geo实现附近的人【redis实战 三】
Spring Boot和Redis Geo实现附近的人【redis实战 三】
29 0
|
22天前
|
NoSQL Java 数据处理
Redis和Spring Boot的绝佳组合:Lua脚本的黑科技
Redis和Spring Boot的绝佳组合:Lua脚本的黑科技
25 0
|
23天前
|
NoSQL Redis
spring-state-machine使用redis持久化
spring-state-machine使用redis持久化
8 0
|
12天前
|
NoSQL Redis 数据安全/隐私保护
Docker中Redis的安装与配置
本文主要讲解如何在Docker环境中搭建Redis环境,并进行相关配置
80 5
Docker中Redis的安装与配置
|
25天前
|
NoSQL Redis Docker
在docker中安装redis,并且阿里云服务器配置
在docker中安装redis,并且阿里云服务器配置
101 1
|
7天前
|
存储 NoSQL Redis
【docker专题_06】docker安装redis
【docker专题_06】docker安装redis
22 1