【项目精讲】Spring框架中如何使用Redis+代码实现(1)

简介

Spring对Redis进行了整合,提供了Spring Data Redis。Spring Data Redis 是 Spring 的一部分,提供了在 Spring 应用中通过简单的配置就可以访问 Redis 服务,对 Redis 底层开发包进行了高度封装。在 Spring 项目中,可以使用Spring Data Redis来简化 Redis 操作。

代码实现

导入maven坐标

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

开启缓存注解

在springboot的启动类(包含@SpringBootApplication)中开启缓存注解@EnableCaching //开启缓存注解 功能

package com.sky;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@EnableCaching //开启缓存注解 功能
@Slf4j
@EnableScheduling // 开启任务调度
public class SkyApplication {
    public static void main(String[] args) {
        SpringApplication.run(SkyApplication.class, args);
        log.info("server started");
    }
}

配置Redis数据源

  1. 在application-dev.yml中添加
    database:指定使用Redis的哪个数据库,Redis服务启动后默认有16个数据库,编号分别是从0到15。
    可以通过修改Redis配置文件来指定数据库的数量。
sky:
  redis:
    host: localhost
    port: 6379
    password: 123456
    database: 10
  1. 在application.yml中读取application-dev.yml中的相关Redis配置
spring:
  profiles:
    active: dev
  redis:
    host: ${sky.redis.host}
    port: ${sky.redis.port}
    password: ${sky.redis.password}
    database: ${sky.redis.database}

编写配置类,创建RedisTemplate对象

当前配置类不是必须的,因为 Spring Boot 框架会自动装配 RedisTemplate 对象,但是默认的key序列化器为JdkSerializationRedisSerializer,导致我们存到Redis中后的数据和原始数据有差别,故设置为StringRedisSerializer序列化器。

package com.sky.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author: Changying
 * @description
 * @create: 2024/3/18 15:34
 */
@Configuration
@Slf4j
public class RedisConfiguration {
    // 直接注入redisConnectionFactory对象
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        log.info("开始创建redis模版对象……");
        RedisTemplate redisTemplate = new RedisTemplate();
        // 设置redis的连接工厂对象
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置redis key的序列化器,主要是为了让图形化界面能够展示出key
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

使用Redis

// 查询Redis需要的对象
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        // 方法改进:首先查询Redis。
        // 1. 查询Redis中是否存在菜品数据
        // 构造redis中的key:dish_分类id
        String key = "dish_" + categoryId;
        // 当时存入redis的是一个list对象,所以这里直接强转为list对象即可
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);

        // 2. 如果存在,直接返回,无需查询数据库
        if (list != null && list.size() > 0){
            return Result.success(list);
        }

        // 3. 如果不存在,查询数据库,并将查询到的数据放入redis中
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
        list = dishService.listWithFlavor(dish);
        // 将查询结果存放到redis中
        // 其实是将list集合对象进行序列化,放入redis中
        redisTemplate.opsForValue().set(key, list);
        return Result.success(list);

参考

https://www.bilibili.com/video/BV1TP411v7v6/?spm_id_from=333.337.search-card.all.click&vd_source=0d2a9b4260ce977e642d073c6ee2260d

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值