techiall / Blog

🍋 [My Blog] See discussions
https://github.com/techiall/Blog/discussions
MIT License
8 stars 1 forks source link

spring boot 配置 redis #45

Open techiall opened 5 years ago

techiall commented 5 years ago

redis maven 依赖配置

如果只是单纯的使用 redis 来当缓存,用缓存注解的话,就不需要导入以下这个依赖。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>RELEASE</version>
        </dependency>

application.yml 配置

根据自己的需要进行配置即可,spring boot 里面都有默认配置。

不全部列举。

spring:
  redis:
    database: 0     # 选择 redis 数据库
    host: localhost # ip
    port: 6379      # 端口
    timeout: 0      # 超时时间(毫秒)
    jedis:
      pool:
        min-idle: 0 # 最小空闲连接
        max-idle: 8 # 最大空闲连接

之后在 main 方法的那个类上,加入 @EnableCaching 注解。

每个要想写入 redis 的类都需要 实现(implements) Serializable 这个接口。 不然会报错。

spring boot 缓存注解

cache 中 key属性的 root 对象。

属性 描述 示例
methodName 当前方法名 #root.methodName
method 当前方法 #root.method.name
target 当前被调用的对象 #root.target
targetClass 当前被调用的对象的class #root.targetClass
args 当前方法参数数组 #root.args[0]
caches 当前被调用的方法使用的Cache #root.caches[0].name

参考链接