SpringBoot(3):springboot集成redis和cache实现缓存

Redis知识点

在项目中对数据的访问往往都是直接访问数据库的方式,但如果对数据的访问量很大或者访问很频繁的话,将会对数据库来很大的压力,甚至造成数据库崩溃。为了解决这类问题redis数据库脱颖而出,redis数据库出现时是以非关系数据库的光环展示在广大程序猿的面前的,后来redis的迭代版本支持了缓存数据、登录session状态(分布式session共享)等。所以又被作为内存缓存的形式应用到大型企业级项目中。

Redis可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。

原理

这里我说的是注解模式,有四个注解,SpringCache缓存原理即注解+拦截器 org.springframework.cache.interceptor.CacheInterceptor 对方法进行拦截处理:

@Cacheable:可标记在类或方法上。标记在类上则缓存该类所有方法的返回值。请求方法时,先在缓存进行key匹配,存在则直接取缓存数据并返回。(key是请求参数,value是方法的返回值)

@CacheEvict:从缓存中移除相应数据。

@CachePut:方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。

@Caching: 多个Cache注解组合使用,比如新增用户时,同时要删除其他缓存,并更新用户信息缓存,即以上三个注解的集合。

springboot整合Redis

1在pom.xml中添加依赖

        <!-- Redis依赖 -->
        <!-- 注意:1.5版本的依赖和2.0的依赖不一样,注意看哦 1.5我记得名字里面应该没有“data”, 2.0必须是“spring-boot-starter-data-redis” 这个才行-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- 缓存: spring cache -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

2在application.yml配置文件添加配置信息

  redis:
    host: 127.0.0.1
    database: 0
    port: 6379
    password:
  cache:
    cache-names: menus_cache

3开启缓存
在项目的入口类上添加@EnableCaching 注解开启缓存

package com.example.lcy;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@MapperScan("com.example.lcy.mapper")
@EnableCaching//@EnableCaching 注解开启缓存
public class LcyApplication {

    public static void main(String[] args) {
        SpringApplication.run(LcyApplication.class, args);
    }
}

4在server中使用缓存

@Service("menuService")
@CacheConfig(cacheNames = "menus_cache")//指明使用的缓存的名字
public class MenuService {
    @Autowired
    MenuMapper menuMapper;

    //将url路径权限表缓存到redis数据库中
    //@Cacheable 注解表示对该方法进行缓存,默认情况下,缓存的key是方法的参数,缓存的value是方法的返回值。当开发者在其他类中调用该方法时,
    // 首先会根据调用参数查看缓存中是否有相关数据,若有,则直才妾使用缓存数据,该方法不会执行,否则执行该方法,执行成功后将返回值缓存起来,但若是在当前类中调用该方法,则缓存不会生效。
    @Cacheable
    public List<Menu> getAllMenusWithRole() {
        System.out.println("menu");
        return menuMapper.getAllMenusWithRole();
    }
}

这里详细描绘了springboot怎么整合redis和cache,我觉得已经写得很棒了。就不在写demo了
参考链接: https://blog.csdn.net/gary_888/article/details/103185659.

发布了34 篇原创文章 · 获赞 1 · 访问量 3154

猜你喜欢

转载自blog.csdn.net/weixin_43700342/article/details/90216146