search
HomeDatabaseRedisHow SpringBoot integrates Redis using @Cacheable and RedisTemplate

How SpringBoot integrates Redis using @Cacheable and RedisTemplate

May 29, 2023 pm 06:19 PM
redisspringboot@cacheable

Made some very simple optimizations to the previous website and added a paging function to the user list.

It is better to consider the loading speed when paginating. If you have to wait a few seconds to change a page, the experience will be very poor.

So I thought of adding a redis cache.

There are two ways for springboot to integrate redis:

  • 1. Use annotations, @EnableCaching @Cacheable . . . etc.

  • 2. Use RedisTemplate

You can use RedisTemplate to operate the cache, which is more flexible and convenient than using annotations. Using annotations should theoretically be faster because it fetches the data directly from the cache without entering the method. RedisTemplate needs to be carried out in the method and perform the judgment of writing logic.

The following is a record of my ideas for caching paging. There must be many shortcomings. I hope everyone can point them out to me.

The business scenario is a backend management system. You don’t need to pay too much attention to real-time data refresh, just set an hour expiration.

My idea is:

When loading a page for the first time, query the data of the first four pages from the database. In this way, wait a little longer for the first time, and the subsequent page changes will be almost No need to wait, this is a better experience. Then every time you change the page, check whether it is in the cache. If it is not useful, add it to the cache.

@RequestMapping("/appUser/{currentPage}")
public R<String> getTableData1(@PathVariable int currentPage) {
    //第一次请求 前面几页用到的概率更大  把后面三页存入redis 减少后面分页请求的时间  以后每次加载页面都把那页放入redis
    // 设置一个小时过期
    Page<AppUser> appUserPage = new Page<AppUser>(currentPage, 12);
    if (currentPage == 1 && !redisTemplate.hasKey(1)) {
        for (int i = 1; i < 5; i++) {
            Page<AppUser> redisPage = new Page<AppUser>(i, 12);
            redisTemplate.opsForValue().set(i, appUserServiceInterface.page(redisPage), 1, TimeUnit.HOURS);
        }
    } else if (!redisTemplate.hasKey(currentPage)) {
        redisTemplate.opsForValue().set(currentPage, appUserServiceInterface.page(appUserPage), 1, TimeUnit.HOURS);
        return R.success((Page<AppUser>) redisTemplate.opsForValue().get(currentPage));
    } else if (redisTemplate.hasKey(currentPage)) {
        return R.success((Page<AppUser>) redisTemplate.opsForValue().get(currentPage));
    }
    return R.success(appUserServiceInterface.page(appUserPage));
}

I tried annotating the data statistics again.

First add the @EnableCaching annotation at startup

The annotation is simple to use. Just add @Cacheable to the method. Before executing the method, it will query whether the redis cache has the corresponding key. If so, Get the value directly, if not, execute the method.

value = "appUserData" is the name of the cache area, and key is the name of the key.

The following key value is appUserData: : userArea

@RequestMapping ("/userArea")
@Cacheable(value = "appUserData",key ="&#39;userArea&#39;")
public R<String> area() {
    List<AppUser> userList = appUserServiceInterface.list();
    List<String> areaList = new ArrayList<>();

    for (AppUser appUser : userList) {
        areaList.add(appUser.getArea());
    }
    //放入map记录每个月份出现的次数
    Map<String, Integer> areaTimes = new HashMap<>();
    for (String s : areaList) {
        if (!areaTimes.containsKey(s)) {
            areaTimes.put(s, 1);
        }else {
            areaTimes.put(s, areaTimes.get(s) + 1);
        }
    }
    //排序
    //自定义比较器
    Comparator<Map.Entry<String, Integer>> valCmp = new Comparator<Map.Entry<String, Integer>>() {
        @Override
        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
            // TODO Auto-generated method stub
            return o2.getValue() - o1.getValue();  // 降序排序,如果想升序就反过来
        }
    };
    //将map转成List,map的一组key,value对应list一个存储空间
    List<Map.Entry<String, Integer>> mapList = new ArrayList<Map.Entry<String, Integer>>(areaTimes.entrySet()); //传入maps实体
    Collections.sort(mapList, valCmp);

    //取前8
    int len = mapList.size();
    for (int i = 0; i < len-8; i++) {
        mapList.remove(8);
    }

    Map<String, String> resMap = new HashMap<>();
    for (Map.Entry<String, Integer> m : mapList) {
        resMap.put(m.getKey(), m.getValue().toString());
    }
    return R.success(resMap);
}

Other notes:

  • @CachePut

  • @Caching

  • @CacheEvict

The above is the detailed content of How SpringBoot integrates Redis using @Cacheable and RedisTemplate. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.