关于Redis集成到SpringBoot中进行简单的增删改

相信很多的初学者学了redis过后,都知道一些命令的运用,但是要把它运用到实际的项目中来,就又是另一回事了,昨天学完redis过后,我把redis运用到 项目中来,顺便做一个笔记,帮助一些需要帮助的人
我们SpringBoot项目该怎么写就怎么写,我给大家一个例子,就关于用户的增删改
我们先把我们的SpringBoot集成redis;
先导入redis依赖

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

application.properties:

spring.redis.host=自己的ip  #默认是localhost
spring.redis.port=端口号		#默认是6379

redis的序列化机制

package com.example.novel.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;
@Configuration
public class RedisConfig {

  //编写我们自己的RedisTemplate
  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    throws UnknownHostException {
    RedisTemplate<String, Object> template = new RedisTemplate<>();

    //配置具体的序列化方式
    template.setConnectionFactory(connectionFactory);

    //自定义Jackson序列化配置
    Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
    jsonRedisSerializer.setObjectMapper(objectMapper);

    //key使用String的序列化方式
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    template.setKeySerializer(stringRedisSerializer);
    //hash的key也是用String的序列化方式
    template.setHashKeySerializer(stringRedisSerializer);
    //value的key使用jackson的序列化方式
    template.setValueSerializer(jsonRedisSerializer);
    //hash的value也是用jackson的序列化方式
    template.setHashValueSerializer(jsonRedisSerializer);
    template.afterPropertiesSet();

    return template;
  }
}

我这个序列化就比较通用了,网上一找一大堆

还有就是redis的封装类,因为SpringBoot 2.0.X过后它的地址已经不是Jedis了,我们直接将它封装过后,也可以像Jedis那样使用

我这个封装类也是比较通用的:
redis封装类

package com.example.novel.until;/**
 * @Auther: http://www.bjsxt.com
 * @Date: 2020/10/24
 * Description: com.kuang.untils
 * version: 1.0
 */

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

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUntils {

  @Autowired
  RedisTemplate redisTemplate;

    // =============================common============================
    /**
     * 指定缓存失效时间
     * @param key  键
     * @param time 时间(秒)
     */
    public boolean expire(String key, long time) {
      try {
        if (time > 0) {
          redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
      return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
      try {
        return redisTemplate.hasKey(key);
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
      if (key != null && key.length > 0) {
        if (key.length == 1) {
          redisTemplate.delete(key[0]);
        } else {
          redisTemplate.delete(CollectionUtils.arrayToList(key));
        }
      }
    }


    // ============================String=============================

    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
      return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */

    public boolean set(String key, Object value) {
      try {
        redisTemplate.opsForValue().set(key, value);
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 普通缓存放入并设置时间
     * @param key   键
     * @param value 值
     * @param time  时间(小时) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */

    public boolean set(String key, Object value, long time) {
      try {
        if (time > 0) {
          redisTemplate.opsForValue().set(key, value, time, TimeUnit.HOURS);
        } else {
          set(key, value);
        }
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 递增
     * @param key   键
     * @param delta 要增加几(大于0)
     */
    public long incr(String key, long delta) {
      if (delta < 0) {
        throw new RuntimeException("递增因子必须大于0");
      }
      return redisTemplate.opsForValue().increment(key, delta);
    }


    /**
     * 递减
     * @param key   键
     * @param delta 要减少几(小于0)
     */
    public long decr(String key, long delta) {
      if (delta < 0) {
        throw new RuntimeException("递减因子必须大于0");
      }
      return redisTemplate.opsForValue().increment(key, -delta);
    }


    // ================================Map=================================

    /**
     * HashGet
     * @param key  键 不能为null
     * @param item 项 不能为null
     */
    public Object hget(String key, String item) {
      return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
      return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     */
    public boolean hmset(String key, Map<String, Object> map) {
      try {
        redisTemplate.opsForHash().putAll(key, map);
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * HashSet 并设置时间
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
      try {
        redisTemplate.opsForHash().putAll(key, map);
        if (time > 0) {
          expire(key, time);
        }
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
      try {
        redisTemplate.opsForHash().put(key, item, value);
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
      try {
        redisTemplate.opsForHash().put(key, item, value);
        if (time > 0) {
          expire(key, time);
        }
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
      redisTemplate.opsForHash().delete(key, item);
    }


    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
      return redisTemplate.opsForHash().hasKey(key, item);
    }


    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     */
    public double hincr(String key, String item, double by) {
      return redisTemplate.opsForHash().increment(key, item, by);
    }


    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     */
    public double hdecr(String key, String item, double by) {
      return redisTemplate.opsForHash().increment(key, item, -by);
    }


    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     * @param key 键
     */
    public Set<Object> sGet(String key) {
      try {
        return redisTemplate.opsForSet().members(key);
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }


    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
      try {
        return redisTemplate.opsForSet().isMember(key, value);
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
      try {
        return redisTemplate.opsForSet().add(key, values);
      } catch (Exception e) {
        e.printStackTrace();
        return 0;
      }
    }


    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
      try {
        Long count = redisTemplate.opsForSet().add(key, values);
        if (time > 0) {
          expire(key, time);
        }
        return count;
      } catch (Exception e) {
        e.printStackTrace();
        return 0;
      }
    }


    /**
     * 获取set缓存的长度
     *
     * @param key 键
     */
    public long sGetSetSize(String key) {
      try {
        return redisTemplate.opsForSet().size(key);
      } catch (Exception e) {
        e.printStackTrace();
        return 0;
      }
    }


    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */

    public long setRemove(String key, Object... values) {
      try {
        Long count = redisTemplate.opsForSet().remove(key, values);
        return count;
      } catch (Exception e) {
        e.printStackTrace();
        return 0;
      }
    }

    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     */
    public List<Object> lGet(String key, long start, long end) {
      try {
        return redisTemplate.opsForList().range(key, start, end);
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }


    /**
     * 获取list缓存的长度
     *
     * @param key 键
     */
    public long lGetListSize(String key) {
      try {
        return redisTemplate.opsForList().size(key);
      } catch (Exception e) {
        e.printStackTrace();
        return 0;
      }
    }


    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     */
    public Object lGetIndex(String key, long index) {
      try {
        return redisTemplate.opsForList().index(key, index);
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public boolean lSet(String key, Object value) {
      try {
        redisTemplate.opsForList().rightPush(key, value);
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 将list放入缓存
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     */
    public boolean lSet(String key, Object value, long time) {
      try {
        redisTemplate.opsForList().rightPush(key, value);
        if (time > 0) {
          expire(key, time);
        }
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }

    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
      try {
        redisTemplate.opsForList().rightPushAll(key, value);
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }

    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
      try {
        redisTemplate.opsForList().rightPushAll(key, value);
        if (time > 0) {
          expire(key, time);
        }
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

    public boolean lUpdateIndex(String key, long index, Object value) {
      try {
        redisTemplate.opsForList().set(key, index, value);
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }


    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */

    public long lRemove(String key, long count, Object value) {
      try {
        Long remove = redisTemplate.opsForList().remove(key, count, value);
        return remove;
      } catch (Exception e) {
        e.printStackTrace();
        return 0;
      }

    }

  }

然后是我们的实体类

package com.example.novel.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserBean implements Serializable {
  //用户id
  private int id;
  //头像
  private String img;
  //用户名
  private String name;
  //用户密码
  private String password;
  //性别
  private  String  sex;
  //余额
  private String balance;
  //权限
  private String limits;
}

Service层

package com.example.novel.service;

import com.example.novel.bean.UserBean;

public interface UserService {

  /**
   * 登录
   * @param userBean
   * @return
   */
  public UserBean loginUser(UserBean userBean);

  /**
   * 修改
   * @param userBean
   * @return
   */
  public int update(UserBean userBean);

  /**
   * 根据id查询数据
   * @param id
   * @return
   */
  public UserBean selectUser(int id);
}

Service实现类

package com.example.novel.serviceImpl;

import com.example.novel.bean.UserBean;
import com.example.novel.mapper.UserMapper;
import com.example.novel.service.UserService;
import com.example.novel.until.RedisUntils;
import jdk.nashorn.internal.parser.Token;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  UserMapper mapper;

  @Autowired
  RedisUntils redisUntils;

  @Override
  public UserBean loginUser(UserBean userBean) {
    UserBean user = mapper.loginUser(userBean);
    redisUntils.set("user_"+user.getId(), user,3);
    System.out.println(redisUntils.get("user_" + user.getId()));
    return user;
  }

  @Override
  public int update(UserBean userBean) {
    int update = mapper.update(userBean);
    if (update!=0){
      String key ="user_"+userBean.getId();
      boolean haskey=redisUntils.hasKey(key); //判断redis缓存存不存在
      if (haskey){
      redisUntils.del(key);
      System.out.println("删除redis缓存======>"+key);
    }
      //查询该用户最新的消息
      UserBean usernew = mapper.selectUser(userBean.getId());
      if (usernew!=null){
        //将用户最新的消息放入redis中
        redisUntils.set(key, usernew, 3);
        System.out.println("放入的新的redis缓存========》"+ redisUntils.get(key));
      }


    }


    return update;
  }

  @Override
  public UserBean selectUser(int id) {
    String key = "user_"+id;
    boolean iskey =redisUntils.hasKey(key);
    if (!iskey){
      UserBean user = mapper.selectUser(id);
      System.out.println("查询数据库获得数据:"+user);
      System.out.println("------------------------------------");
      //写入缓存
      redisUntils.set(key, user);
      return user;
    }else {
      UserBean user = (UserBean) redisUntils.get(key);
      System.out.println("从缓存中获得数据:"+user);
      System.out.println("------------------------------------");
      return user;
    }
  }
}

mapper层

@Mapper
@Repository
public interface UserMapper {
  //登录
  public  UserBean loginUser(UserBean userBean);

  //修改
  public int update(UserBean userBean);
  //根据id查询数据
  public UserBean selectUser(int id);
}

mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.novel.mapper.UserMapper">
    <resultMap id="User" type="UserBean">
        <result property="id" column="id"/>
        <result property="img" column="img"/>
        <result property="name" column="name"/>
        <result property="password" column="password"/>
        <result property="sex" column="sex"/>
        <result property="balance" column="balance"/>
        <result property="limits" column="limits"/>
    </resultMap>

    <!--登录-->
    <select id="loginUser" resultMap="User">
        select * from user where name=#{name} AND  password=#{password};
    </select>

    <!--修改-->
    <update id="update" parameterType="UserBean">
        update user
        <set>
            <if test="name!=null">
                name =#{name},
            </if>
            <if test="password!=null">
                password=#{password},
            </if>
            <if test="img!=null">
                img=#{img},
            </if>
            <if test="sex!=null">
                sex=#{sex},
            </if>
            <if test="balance!=null">
                balance=#{balance},
            </if>
            <if test="limits!=null">
                limits=#{limits},
            </if>
        </set>
        where id=#{id}
    </update>

    <!--查询用户信息-->
    <select id="selectUser" resultMap="User">
        select * from user where id=#{id};
    </select>
</mapper>

Controller层

package com.example.novel.controller;

import com.example.novel.bean.ResultBean;
import com.example.novel.bean.ResultBean2;
import com.example.novel.bean.UserBean;
import com.example.novel.service.BookShelfService;
import com.example.novel.service.UserService;
import com.example.novel.until.JWTUntils;
import com.example.novel.until.ResultUntil;
import com.example.novel.until.ResultUntil2;
import io.jsonwebtoken.Claims;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.invoke.SerializedLambda;
import java.util.UUID;
@RestController
public class LoginController {

  @Autowired
  UserService userService;

  /**
   * 登录
   * @param userBean
   * @param request
   * @return
   */
  @PostMapping("/user/login")
  public ResultBean2 loginUser(UserBean userBean, HttpServletRequest request){
    UserBean user =userService.loginUser(userBean);
    if (user!=null){
   ResultUntil2.result(ResultUntil.code200,token,user,"登录成功");
    }else {
     return ResultUntil2.result(ResultUntil.code500, " ","", "登录失败");
    }

  }

  /**
   * 跳转到修改界面
   * @param id
   * @return
   */
  @GetMapping("/topageUpdate")
  public ResultBean toPageUpdate(int id){
    UserBean user =userService.selectUser(id);
    return ResultUntil.result(ResultUntil.code200,user,"查询成功");
   }

  @PostMapping("/updateUser")
  public ResultBean updateUser(UserBean userBean){
    int count=userService.update(userBean);
    return ResultUntil.result(ResultUntil.code200,count,"修改成功");
  }

}

这就是我自己整理的东西,都很简单,关于redis的话,我是把它写到了Service实现类里面的,希望这些对大家有帮助,
对了还有一个,写了一个返回类

package com.example.novel.until;

import com.example.novel.bean.ResultBean;
/**
 * 返回数据封装类
 */
public class ResultUntil {
  public static final int code200=200;

  public static final int code401=401;

  public static final int code500=500;

  public static ResultBean result(int code,Object data,String msg){
    return new ResultBean(code,data,msg);
  }
}


版权声明:本文为weixin_44281208原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。