redis案例:springboot+mybatis+redis

说明

建表

CREATE TABLE `weibo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(1024) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '微博内容',
  `like` int(255) DEFAULT NULL COMMENT '点赞数量',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=124 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

创建 springboot 工程

https://www.malaoshi.top/show_1EF5qXjMmlZR.html

整合 mybatis

https://www.malaoshi.top/show_1EF5gW27Vba9.html

整合 redis

https://www.malaoshi.top/show_1IXHUQbjHVa.html

实体类

package com.std.entity;

import java.io.Serializable;

/**
 * @author 
 * 
 */
public class Weibo implements Serializable {
    private Integer id;

    /**
     * 微博内容
     */
    private String content;

    /**
     * 点赞数量
     */
    private Integer like;

    private static final long serialVersionUID = 1L;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Integer getLike() {
        return like;
    }

    public void setLike(Integer like) {
        this.like = like;
    }

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        Weibo other = (Weibo) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent()))
            && (this.getLike() == null ? other.getLike() == null : this.getLike().equals(other.getLike()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode());
        result = prime * result + ((getLike() == null) ? 0 : getLike().hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", content=").append(content);
        sb.append(", like=").append(like);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

dao接口

MyBatisBaseDao

import java.io.Serializable;

/**
 * DAO公共基类,由MybatisGenerator自动生成请勿修改
 * @param <Model> The Model Class 这里是泛型不是Model类
 * @param <PK> The Primary Key Class 如果是无主键,则可以用Model来跳过,如果是多主键则是Key类
 */
public interface MyBatisBaseDao<Model, PK extends Serializable> {
    int deleteByPrimaryKey(PK id);

    int insert(Model record);

    int insertSelective(Model record);

    Model selectByPrimaryKey(PK id);

    int updateByPrimaryKeySelective(Model record);

    int updateByPrimaryKey(Model record);
}

WeiboDAO

import com.std.entity.Weibo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * WeiboDAO继承基类
 */
@Mapper
public interface WeiboDAO extends MyBatisBaseDao<Weibo, Integer> {
}

dao.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.std.dao.WeiboDAO">

  <resultMap id="BaseResultMap" type="com.std.entity.Weibo">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="content" jdbcType="VARCHAR" property="content" />
    <result column="like" jdbcType="INTEGER" property="like" />
  </resultMap>

  <sql id="Base_Column_List">
    id, content, `like`
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from weibo
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from weibo
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.std.entity.Weibo">
    insert into weibo (id, content, `like`
      )
    values (#{id,jdbcType=INTEGER}, #{content,jdbcType=VARCHAR}, #{like,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.std.entity.Weibo">
    insert into weibo
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="content != null">
        content,
      </if>
      <if test="like != null">
        `like`,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="content != null">
        #{content,jdbcType=VARCHAR},
      </if>
      <if test="like != null">
        #{like,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.std.entity.Weibo">
    update weibo
    <set>
      <if test="content != null">
        content = #{content,jdbcType=VARCHAR},
      </if>
      <if test="like != null">
        `like` = #{like,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.std.entity.Weibo">
    update weibo
    set content = #{content,jdbcType=VARCHAR},
      `like` = #{like,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

service

service接口

package com.std.service;

import com.std.entity.Weibo;

public interface IWeiboService {

    public Weibo selectById(Integer id);

    public int like(Integer id);
}

service实现类

package com.std.service.impl;


import com.std.dao.WeiboDAO;
import com.std.entity.Weibo;
import com.std.redis.RedisUtil;
import com.std.service.IWeiboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class WeiboSrvImpl implements IWeiboService {

    @Resource
    private WeiboDAO dao;

    @Autowired
    private RedisUtil redisUtil;

    public Weibo selectById(Integer id) {

        String keyOfRedis="weibo_"+id;

        Weibo ret=redisUtil.get(keyOfRedis);
        //判断obj是否为null
        if(ret==null){
            // 如果为null,要查询mysql
            ret=dao.selectByPrimaryKey(id);

            //将查询结果存入redis
            boolean b=redisUtil.set(keyOfRedis,ret);
            System.out.println("添加redis的结果:"+b);

        }


        return ret;
    }

    @Override
    public int like(Integer id) {
        String keyOfRedis="weibo_"+id;

        Weibo weibot=redisUtil.get(keyOfRedis);

        int ret=0;
        //判断obj是否为null
        if(weibot==null){
            // 如果为null,要查询mysql
            weibot=dao.selectByPrimaryKey(id);
        }

        //点赞+1
        ret=weibot.getLike()+1;
        weibot.setLike(ret);
        boolean b=redisUtil.set(keyOfRedis,weibot);
        System.out.println("添加redis的结果:"+b);

        return ret;
    }
}

controller

package com.std.ctrl;


import com.std.entity.Weibo;
import com.std.service.IWeiboService;
import com.std.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/weibo")
public class WeiboCtrl {

    //也是可以注入对象,类似@Resource,但有区别
    @Autowired
    private IWeiboService service;

    @RequestMapping("/showById")
    public JsonResult showById(Integer id){

        Weibo weibo = service.selectById(id);

        JsonResult jr=null;
        if(weibo!=null){
            jr=JsonResult.success("",weibo);
        }else{
            jr=JsonResult.fail(JsonResult.CODE_RECORD_NO_EXIST,"查无此记录!");
        }

        return jr;
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @RequestMapping("/like")
    public JsonResult like(Integer id){
        int like=service.like(id);

        return JsonResult.success(null,like);
    }

}

原文出处:/show_1IX2vrMJOqNM.html