spring boot整合 Redis

Spring Boot 整合 Redis

  1. pom.xml依赖:
xml 复制代码
		  <!-- redis依赖 -->
		  <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
  1. application.yml配置
yaml 复制代码
spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
        username: root
        password: 5508769123
    data:
        #Redis 相关配置
        redis:
            host: localhost
            port: 6379  #Redis端口号,具体可在Redis的.conf文件中查看
            #password: 123456
            database: 0
            jedis:
                #Redis连接池配置
                pool:
                    max-active: 8
                    max-wait: 1ms
                    max-idle: 4
                    min-idle: 0
    cache:
     redis:
        time-to-live: 1800000 #设置缓存过期时间单位毫秒ms
  1. 在启动类上添加@EnableCaching注解
java 复制代码
package com.mercurows;

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

@SpringBootApplication
@EnableCaching
public class SpringbootCacheDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootCacheDemoApplication.class, args);
	}
}
  1. 在需要的地方进行Cache缓存操作,这里在controller中(框架为springboot)
java 复制代码
package com.mercurows.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mercurows.entity.User;
import com.mercurows.service.UserService;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private UserService userService;

    /**
     * CahcePut:将方法返回值放入缓存
     * @Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     */
    @CachePut(value = "userCache",key = "#user.id")
    @PostMapping
    public User save(User user) {
        userService.save(user);
        return user;
    }

    /**
     * CacheEvict:清理指定缓存
     * value:缓存的名称,每个缓存名称下面可以有多个key,同时也是指定清理缓存的名称
     * key:缓存的key
     * allEntries:表明清理缓存时直接清理所有的
     */
    @CacheEvict(value = "userCache", key = "#p0",allEntries = true)
    // @CacheEvict(value = "userCache",key = "#root.args[0]")
    // @CacheEvict(value = "userCache",key = "#id")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        userService.removeById(id);
    }

    // @CacheEvict(value = "userCache",key = "#p0.id")
    // @CacheEvict(value = "userCache",key = "#user.id")
    // @CacheEvict(value = "userCache",key = "#root.args[0].id")
    @CacheEvict(value = "userCache",key = "#result.id")
    @PutMapping
    public User update(User user) {
        userService.updateById(user);
        return user;
    }

    /**
     * Cacheable:在方法执行强spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据,
     * 若没有数据则将方法结果存入缓存、
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     * unless:满足条件则不缓存,即下次仍为null时还走查询而不是走缓存
     */
    @Cacheable(value = "userCache", key = "#id",unless = "#result == null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id) {
        User user = userService.getById(id);
        return user;
    }

    @Cacheable(value = "userCache",key = "#user.id+'_'+#user.name")
    @GetMapping("/list")
    public List<User> list(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getId() != null, User::getId, user.getId());
        queryWrapper.eq(user.getName() != null, User::getName, user.getName());
        List<User> list = userService.list(queryWrapper);
        return list;
    }
}

value的作用就是给被缓存的方法起个名字,下次再请求这个方法的时候就知道去找那个缓存了。

缓存的实际结果通常是根据方法的参数计算得到的。每个不同的参数组合可以产生不同的缓存结果。这些缓存结果通常是以键值对(key-value pairs)的形式存储的,其中键(key)是用于标识不同参数组合的唯一标识,而值(value)则是对应的方法执行结果。

当使用value属性来定义缓存名称时,通常是在缓存配置中将这个名称与具体的方法和其参数关联起来。在缓存中,会维护一个键值对的数据结构,其中键是由方法的参数组成的,而值是方法执行的结果。

启动项目时记得 启动redis服务:redis-server.exe文件

相关推荐
柚个朵朵1 小时前
Spring的Validation,这是一套基于注解的权限校验框架
java·后端·spring
程序员小杰@1 小时前
【MCP教程系列】SpringBoot 搭建基于 Spring AI 的 SSE 模式 MCP 服务
人工智能·spring boot·spring
清幽竹客1 小时前
redis数据结构-02(INCR、DECR、APPEND)
数据结构·redis
程序员buddha2 小时前
Spring & Spring Boot 常用注解整理
java·spring boot·spring
呦呦鹿鸣Rzh2 小时前
redis
数据库·redis·缓存
Asus.Blogs2 小时前
为什么go语言中返回的指针类型,不需要用*取值(解引用),就可以直接赋值呢?
开发语言·后端·golang
C_V_Better2 小时前
Java Spring Boot 控制器中处理用户数据详解
java·开发语言·spring boot·后端·spring
胡子洲2 小时前
Spring Boot 应用中实现基本的 SSE 功能
java·spring boot·后端
非著名架构师2 小时前
SpringBoot整合MQTT实战:基于EMQX构建高可靠物联网通信,从零到一实现设备云端双向对话
spring boot·mqtt·emqx
贰拾wan3 小时前
【Java-EE进阶】SpringBoot针对某个IP限流问题
java·spring boot·后端·idea