Home > Database > Redis > How SpringBoot integrates Redis using @Cacheable and RedisTemplate

How SpringBoot integrates Redis using @Cacheable and RedisTemplate

PHPz
Release: 2023-05-29 18:19:41
forward
1441 people have browsed it

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));
}
Copy after login

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);
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template