redis在springboot中的配置及使用

文章介绍了如何在SpringBoot项目中配置Redis,包括添加依赖、配置文件设置以及创建RedisUtil工具类来操作Redis,如存取数据。此外,文章还展示了如何通过Redis生成和验证登录验证码,以及使用JSONResult返回信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

rides的基本配置

配置pom插件,rides原理就相当于key,value

<!--集成redis-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-redis</artifactId>
  <version>1.4.1.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis</artifactId>
</dependency>

在application.yml添加redis配置,在spring下写redis,然后配置host,port,password

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
    username: root
    password: 2020
    driver-class-name: com.mysql.cj.jdbc.Driver
  redis:
    host: 120.48.17.2
    port: 6379
    password: 123456
mybatis:
  mapper-locations: classpath:mapper/*.xml  #??mapper??xml??????
  type-aliases-package: com.qcby.springbootdemo2.model  #???????
server:
  port: 8080

定义redis存储key和value方法,也可以把这个当成一个工具类

package com.qcby.springbootdemo2.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component//这里是将这个方法托管给spring
    public class RedisUtil {
        @Autowired
        RedisTemplate<Object,Object> redisTemplate;//自动装载springboot内部集成的redis方法

        public void insert(Object key,Object value){
            BoundValueOperations<Object,Object > stringStringBoundValueOperations = redisTemplate.boundValueOps(key);//设置redis的key是输入的key
            stringStringBoundValueOperations.set(value,1, TimeUnit.MINUTES);//设置redis的value为输入的value,设置生存时间是1,单位是分钟
        }
        
         public Object  select(Object key){
        return redisTemplate.boundValueOps(key).get();
    	}

   		public void del(Object key){
        redisTemplate.delete(key);
   		}
    }

在controller需要写这些

package com.qcby.springbootdemo2.controller;

import com.alibaba.fastjson.JSONObject;
import com.qcby.springbootdemo2.model.User;
import com.qcby.springbootdemo2.service.UserService;
import com.qcby.springbootdemo2.util.JsonResult;
import com.qcby.springbootdemo2.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class UserController {//这里是controller方法
    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;//这里调用的是上面redisUtil工具类

    @PostMapping("/redis")
    public JSONObject redis (@RequestBodyUser user){
        JSONObject jsonObject = new JSONObject();
        redisUtil.insert(user.getAccount(),user.getPassword());//调用上面insert方法,给他传key,value
        log.info("这是redis的value:",redisUtil.select(user.getAccount()));//调用select方法,通过传入参key查出对应的value
        //这里rides只是临时存储在了rides服务器内存里,并没有存在数据库里,如果需要存到数据库里还需要自己定义insert语句添加到数据库
        return jsonObject;
    }
}

定义一个返回信息的模板--JsonResult工具类

package com.qcby.springbootdemo2.util;

import com.alibaba.fastjson.JSONObject;

public class JsonResult {

    public static JSONObject success(String msg,Object data){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg",msg);
        jsonObject.put("data",data);
        return jsonObject;
    }

    public static JSONObject error(String msg){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg",msg);
        return jsonObject;
    }
}

rides的实际案例应用---获取验证码并设置验证码的生存时间

service接口添加logincode方法

package com.qcby.springbootdemo2.service;

import com.qcby.springbootdemo2.model.User;

public interface UserService {

    String getLoginCode(String account);

}

service实现logincode方法

package com.qcby.springbootdemo2.service.UserServiceImpl;

import com.qcby.springbootdemo2.dao.UsersDao;
import com.qcby.springbootdemo2.model.User;
import com.qcby.springbootdemo2.service.UserService;
import com.qcby.springbootdemo2.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersDao usersDao;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public String getLoginCode(String account) {
        Object select = redisUtil.select(account);//查询之前生成的验证码有没有过期
        if (select!=null){
            return "请勿重复生成验证吗";
        }

        String logincode = UUID.randomUUID().toString().substring(0, 4);//UUID生成随机数并截取4位作为验证码
        redisUtil.insert(account,logincode);//调用redisUtil方法传参key为当前账号,value为刚才生成的验证吗
        return logincode;
    }


}

controller调用

ackage com.qcby.springbootdemo2.controller;

import com.alibaba.fastjson.JSONObject;
import com.qcby.springbootdemo2.model.User;
import com.qcby.springbootdemo2.service.UserService;
import com.qcby.springbootdemo2.util.JsonResult;
import com.qcby.springbootdemo2.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;
//这里是添加redis的key和value值
    @PostMapping("/redis")
    public JSONObject redis (@RequestBody User user){
        JSONObject jsonObject = new JSONObject();
        redisUtil.insert(user.getAccount(),user.getPassword());
        log.info("这是redis的value:",redisUtil.select(user.getAccount()));

        return jsonObject;
    }
//这里是调用获取验证码方法
    @PostMapping("/getlogincode")
    public JSONObject getlogincode (@RequestBody User user){
        JSONObject jsonObject = new JSONObject();
        String loginCode = userService.getLoginCode(user.getAccount());//调用后端验证码接口传入参账号得到验证码
        if (loginCode.equals("请勿重复生成验证吗")){
            jsonObject=JsonResult.error("请勿重复生成验证吗");
        }else {
            jsonObject=JsonResult.success("获取验证码成功",loginCode);
        }
        return jsonObject;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值