spring boot整合 Redis

Spring Boot 整合 Redis

  1. pom.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配置
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注解
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)
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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 可以很方便地与 Redis 进行集成。以下是一个简单的 Spring Boot 整合 Redis 的示例: 1. 添加 Redis 依赖 在 `pom.xml` 添加 Redis 相关依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置 Redis 连接信息 在 `application.properties` 文件中配置 Redis 的连接信息: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 如果 Redis 没有设置密码,则 `spring.redis.password` 可以不用配置。 3. 编写 Redis 配置类 创建一个 Redis 配置类,用于配置 RedisTemplate 和 RedisConnectionFactory: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Object.class)); return redisTemplate; } @Bean public RedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName("localhost"); redisStandaloneConfiguration.setPort(6379); return new JedisConnectionFactory(redisStandaloneConfiguration); } } ``` 4. 使用 RedisTemplate 操作 Redis 在需要使用 Redis 的地方注入 RedisTemplate,然后就可以使用其提供的方法操作 Redis 了: ```java @RestController @RequestMapping("/redis") public class RedisController { @Autowired private RedisTemplate<String, Object> redisTemplate; @GetMapping("/set") public String set(String key, String value) { redisTemplate.opsForValue().set(key, value); return "success"; } @GetMapping("/get") public String get(String key) { Object value = redisTemplate.opsForValue().get(key); return value != null ? value.toString() : ""; } } ``` 以上示例中,我们使用了 RedisTemplate 的 `opsForValue` 方法来进行 Redis 的读写操作。 这样,我们就完成了 Spring Boot 整合 Redis 的操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值