缓存优化--使用Redis将项目进行优化

缓存优化–使用Redis

  • 问题描述:

用户数量多,系统访问量大的时候,用户发送大量的请求,导致频繁访问数据库,系统性能下降,用户体验差。

1、环境搭建

  • maven坐标

在项目的pom.xml文件中导入spring data redis的maven坐标:

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
     </dependency>
  • 配置文件

在项目的application. ym1中加入redis相关配置:

spring:
  redis:
    host: localhost
    port: 6379
    password: 123456
    database: 0 #操作的是0号数据库
  • 配置类

在项目中加入配置类Redisconfig:

package com.mannor.reggie_take_out.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
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;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        //默认的Key序列化器为:JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer()); //String !!!
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

2、缓存短信验证码

2.1、实现思路

  • 之前我学习的项目已经实现了移动端手机验证码登录,随机生成的验证码我们是保存在HttpSession中的。(点击产看基于阿里云的短信验证实现文章)现在需要改造为将验证码缓存在Redis中,具体的实现思路如下:
1、在服务端UserController中注入RedisTemplate对象,用于操作Redis
2、在服务端UserController的sendMsg方法中,将随机生成的验证码缓存到Redis中,并设置有效期为5分钟
3、在服务端UserController的login方法中,从Redis中获取缓存的验证码,如果登录成功则删除Redis中的验证码

2.2、代码改造

将session改造成redis(存在注释):

package com.mannor.reggie_take_out.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mannor.reggie_take_out.Utils.SMSUtils;
import com.mannor.reggie_take_out.Utils.ValidateCodeUtils;
import com.mannor.reggie_take_out.common.R;
import com.mannor.reggie_take_out.entity.User;
import com.mannor.reggie_take_out.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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

   @Autowired
   private UserService userService;

   @Autowired
   private RedisTemplate redisTemplate;

   /**
    * 发送短信验证码
    *
    * @param user
    * @param session
    * @return
    */
   @PostMapping("/sendMsg")
   public R<String> sendMsg(@RequestBody User user, HttpSession session) {
       //获取手机号
       String phone = user.getPhone();
       if (StringUtils.isNotEmpty(phone)) {
           //生成随机的6位验证码
           String code = ValidateCodeUtils.generateValidateCode(6).toString();
           log.info("code={}", code);
           //调用阿里云提供的短信服务API完成发送短信
           SMSUtils.sendMessage("mannor的博客", "SMS_4203645", phone, code);
           //需要将生成的验证码保存到Session
           //session.setAttribute(phone, code);
           //将生成的验证码报错到redis中,并且设置5分钟失效
           redisTemplate.opsForValue().set(phone, code, 5L, TimeUnit.SECONDS);
           return R.success("短信验证码发送成功!");
       }
       return R.error("短信验证码发送失败!");
   }

   @PostMapping("/login")
   public R<User> login(@RequestBody Map map, HttpSession session) {
       log.info("map={}", map);
       //获取手机号
       String phone = map.get("phone").toString();
       //获取验证码
       String code = map.get("code").toString();
       //从Session中获取保存的验证码
       //Object codeInSession = session.getAttribute(phone);
       //进行验证码的比对(页面提交的验证码和Session中保存的验证码比对)

       //从redis中获得缓存的验证码
       Object codeInSession = redisTemplate.opsForValue().get(phone);
       if (codeInSession != null && codeInSession.equals(code)) {
           // 如果能够比对成功,说明登录成功
           LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
           lambdaQueryWrapper.eq(User::getPhone, phone);
           User user = userService.getOne(lambdaQueryWrapper);
           if (user == null) {
               //判断当前手机号对应的用户是否为新用户,如果是新用户就自动完成注册
               user = new User();
               user.setPhone(phone);
               user.setStatus(1);
               userService.save(user);
           }
           session.setAttribute("user", user.getId());
           //如果用户登录成功那就删除redis中缓存的验证码
           redisTemplate.delete(phone);
           return R.success(user);
       }

}

3、缓存菜品数据

3.1、实现思路

  • 之前我已经实现了移动端菜品查看功能,对应的服务端方法为DishController的list方法,此方法会根据前端提交的查询条件进行数据库查询操作。在高并发的情况下,频繁查询数据库会导致系统性能下降,服务端响应时间增长。现在需要对此方法进行缓存优化,提高系统的性能。

具体的实现思路如下:

1、改造DishController的list方法,先从Redis中获取菜品数据,如果有则直接返回,无需查询数据库;如果没有则查询数据库,并将查询到的菜品数据放入Redis。
2、改造DishController的save和update方法,加入清理缓存的逻辑。

注意:在使用缓存过程中,要注意保证数据库中的数据和缓存中的数据一致,如果数据库中的数据发生变化,需要及时清理缓存数据。

3.2、代码改造

以点餐系统菜品查询为例

原先的list查询代码:

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

   @Autowired
   private DishService dishService;

   @Autowired
   private DishFlavorService dishFlavorService;

   @Autowired
   private CategoryService categoryService;

   /**
    * 套餐管理中添加套餐中的菜品
    *
    * @param dish
    * @return
    */
   @GetMapping("/list")
   public R<List<DishDto>> list(Dish dish) {
       //构造查询条件
       LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
       //添加条件,查询状态为1(起售状态)的菜品
       queryWrapper.eq(Dish::getStatus, 1);

       //添加排序条件
       queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

       List<Dish> list = dishService.list(queryWrapper);

       List<DishDto> dishDtoList = list.stream().map((item) -> {
           DishDto dishDto = new DishDto();

           BeanUtils.copyProperties(item, dishDto);

           Long categoryId = item.getCategoryId();//分类id
           //根据id查询分类对象
           Category category = categoryService.getById(categoryId);

           if (category != null) {
               String categoryName = category.getName();
               dishDto.setCategoryName(categoryName);
           }

           //当前菜品的id
           Long dishId = item.getId();
           LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
           lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
           //SQL:select * from dish_flavor where dish_id = ?
           List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
           dishDto.setFlavors(dishFlavorList);
           return dishDto;
       }).collect(Collectors.toList());
       return R.success(dishDtoList);
   }

}

redis缓存后的查询代码:

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 套餐管理中添加套餐中的菜品
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;
        //动态的构造一个key,用于redis缓存
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //从redis获取缓存的数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null) {
            //如果存在,直接返回,不需要查询数据库
            return R.success(dishDtoList);
        }
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件,查询状态为1(起售状态)的菜品
        queryWrapper.eq(Dish::getStatus, 1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //不存在,就需要查询数据库,将查询道德数据缓存到redis中华
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);//设置60分钟后过期

        return R.success(dishDtoList);
    }
}

当然,更新数据之后也需要将缓存清理(以update为例):

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("更新菜品的参数dishDto={}", dishDto);
        dishService.updateWithFlavor(dishDto);

        //更新之后清理菜品数据,免得产生脏数据
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //精确清理-->清理某个分类下的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        
        return R.success("菜品更新成功");
    }

使用Spring Cache进行开发会更简洁,更容易,文章推荐:Spring Cache的介绍以及怎么使用(redis)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Go微服务中使用Redis缓存是一种常见的做法。通过引入动态缓存配置文件和初始化dynamic_cache.go中的公有值,可以实现对Redis缓存的配置和初始化。在配置文件中使用include命令引入动态缓存配置文件(dynamicache.conf),可以更方便地管理和修改缓存配置。在sysinit/sysinit.go文件中,有一个函数initDynamicCache用于初始化dynamic_cache.go中的公有值,并初始化Redis配置。可以通过设置MaxOpen、MaxIdle和ExpireSec等参数来配置Redis缓存的最大连接数、最大空闲连接数和缓存过期时间。通过调用dynamicache.InitCache()方法来初始化Redis缓存。这样就可以在Go微服务中使用go-redis缓存了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [go-redis-cache:使用Redis缓存进行微服务](https://download.csdn.net/download/weixin_42131628/16618478)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Go项目优化——动态缓存Redis使用](https://blog.csdn.net/weixin_52000204/article/details/127338089)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曼诺尔雷迪亚兹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值