使用Springboot整合redis与mysql

2020-05-02 16:00:40来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

使用Springboot整合redis与mysql

使用layui实现前台页面,实现用户的增删改查

环境参数

  • 开发工具:IDEA
  • 基础环境:Maven+JDK8
  • 主要技术:SpringBoot、redis,mysql,swagger框架与layui前段框架
  • SpringBoot版本:2.2.6

 

实现步骤如下:

1.添加依赖

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

        <!-- mybatisPlus 核心库 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.6</version>
        </dependency>

        <!-- thymeleaf模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

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

        <!--    mysql驱动包    -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.41</version>
        </dependency>

        <!-- 引入阿里数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--mybatis-plus 代码生成器依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>

        <!--  swagger 依赖   -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

 

2.实体层

package com.ckf.springboot_mysql_redis.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.stereotype.Component;

/**
 * @author 安详的苦丁茶
 * @since 2020-05-02
 */
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("users")
public class Users implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(type = IdType.AUTO)
    private Integer userId;

    private String userIp;

    private String userName;

    private String password;

    private String email;

    private String registerTime;

    private String updateTime;

    private Integer age;

    private String telephoneNumber;

    private String nickname;

    private Integer state;


}

 

3.业务service层

package com.ckf.springboot_mysql_redis.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ckf.springboot_mysql_redis.entity.Users;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ckf.springboot_mysql_redis.model.ResultFormat;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author 安详的苦丁茶
 * @since 2020-05-02
 */
public interface UsersService extends IService<Users> {

    /**
     * 全查询用户信息
     * @return
     */
    IPage<Users> selectUsersList(Page<Users> page);
    
    /**
     * 添加用户
     * @param users
     * @return
     */
    ResultFormat saveUsers(Users users);

    /**
     * 修改用户
     * @param users
     * @return
     */
    ResultFormat updateUsers(Users users);
    
    /**
     * 删除用户
     * @param userId
     * @return
     */
    Integer deleteUsersId(Integer userId);

}

 

4. service实现层

package com.ckf.springboot_mysql_redis.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ckf.springboot_mysql_redis.controller.UsersController;
import com.ckf.springboot_mysql_redis.entity.Users;
import com.ckf.springboot_mysql_redis.mapper.UsersMapper;
import com.ckf.springboot_mysql_redis.model.ResultFormat;
import com.ckf.springboot_mysql_redis.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ckf.springboot_mysql_redis.utils.RedisUtil;
import com.ckf.springboot_mysql_redis.utils.ResultUtil;
import com.ckf.springboot_mysql_redis.utils.TimeUtitl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 安详的苦丁茶
 * @since 2020-05-02
 */
@Service
@Transactional
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    private Logger logger = LoggerFactory.getLogger(UsersService.class);

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 全查询
     * @param page
     * @return
     */
    @Override
    public IPage<Users> selectUsersList(Page<Users> page) {
        logger.info("-----------------进入service实现层 全查询用户信息-----------------");
        return usersMapper.selectUsersList(page);

    }

    /**
     * 添加
     * @param users
     * @return
     */
    @Override
    public ResultFormat saveUsers(Users users) {
        logger.info("-----------------进入service实现层 添加用户信息-----------------");

        /**
         * 查询用户名称是否存在
         * 如果存在那就返回提示已经存在
         * 如果不存在就执行添加
         */
        AbstractWrapper abstractWrapper = new QueryWrapper<Users>();
        abstractWrapper.eq("user_name", users.getUserName());
        Users UsersWrapperGet = usersMapper.selectOne(abstractWrapper);
        logger.info("pgLabelsWrapperGet={}", UsersWrapperGet);

        if (UsersWrapperGet != null) {
            return ResultUtil.error(101, "用户名称已存在");
        }
        users.setState(0);

        Integer insert = usersMapper.insert(users);

        if (insert > 0) {
            redisUtil.lSet("userId", users.getUserId());
            redisUtil.set("users:" + users.getUserIp(), users);
        }
        return ResultUtil.success();
    }

    /**
     * 修改
     * @param users
     * @return
     */
    @Override
    public ResultFormat updateUsers(Users users) {
        logger.info("-----------------进入service实现层 修改用户信息-----------------");
        /**
         * 查询用户名称是否存在
         * 如果存在那就返回提示已经存在
         * 如果不存在就执行添加
         */
        AbstractWrapper Wrapper = new QueryWrapper<Users>();
        Wrapper.eq("user_name", users.getUserName());
        Users UsersWrapperGet = usersMapper.selectOne(Wrapper);
        logger.info("pgLabelsWrapperGet={}", UsersWrapperGet);

        if (UsersWrapperGet != null) {
            return ResultUtil.error(101, "用户名称已存在");
        }
        users.setState(0);

        Integer updateById = usersMapper.updateById(users);

        if (updateById > 0) {
            redisUtil.set("users:" + users.getUserId(), users);
        }
        return ResultUtil.success();
    }

    /**
     * 删除
     * @param userId
     * @return
     */
    @Override
    public Integer deleteUsersId(Integer userId) {
        logger.info("-----------------进入service实现层 删除用户信息-----------------");
        Integer deleteById = usersMapper.deleteById(userId);

        if (deleteById > 0) {
            Long delete = redisUtil.delete("users:" + String.valueOf(userId));
        }
        return deleteById;
    }
}

 

5.controller层

package com.ckf.springboot_mysql_redis.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ckf.springboot_mysql_redis.entity.Users;
import com.ckf.springboot_mysql_redis.model.ResultFormat;
import com.ckf.springboot_mysql_redis.model.ResultFormatPaging;
import com.ckf.springboot_mysql_redis.service.UsersService;
import com.ckf.springboot_mysql_redis.utils.ResultPagingUtil;
import com.ckf.springboot_mysql_redis.utils.ResultUtil;
import com.ckf.springboot_mysql_redis.utils.TimeUtitl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 安详的苦丁茶
 * @since 2020-05-02
 */
@Api(tags = "用户信息管理")
@RestController
@RequestMapping("/users")
public class UsersController {

    private Logger logger = LoggerFactory.getLogger(UsersController.class);


    @Autowired
    private UsersService usersService;



    /**
     * 分页全查询用户信息
     *
     * @return
     */
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "Integer", defaultValue = "1"),
            @ApiImplicitParam(name = "limit", value = "每页记录数", required = true, dataType = "Integer", defaultValue = "5")
    })

    /**
     * 全查询分类信息
     *
     * @return
     */
    @ApiOperation("查询用户信息接口")
    @GetMapping("/list")
    public ResultFormatPaging pgUsersList(Integer page, Integer limit) {
        logger.info("-------------------进入用户查询controller层--------------------------");
        if (page != null && limit != null) {
            logger.info("page={}", page);
            logger.info("limit={}", limit);

            System.out.println("ok");
            Page<Users> users = new Page<>(page, limit);
            System.out.println("ok");
            IPage<Users> pgUsersIPage = usersService.selectUsersList(users);
            List<Users> pgUsersList = pgUsersIPage.getRecords();

            logger.info("usersList=={}", pgUsersList);

            return ResultPagingUtil.pagingSuccess(0, (int) pgUsersIPage.getTotal(), pgUsersList);
        }

        return ResultPagingUtil.pagingError(200, 0, "系统匆忙,查询异常");


    }


    /**
     * 添加用户信息
     *
     * @param users
     * @return
     */
    @ApiOperation("添加用户信息接口")
    @PostMapping("/save")
    @ResponseBody
    public ResultFormat savePgSorts(Users users) {
        users.setRegisterTime(TimeUtitl.dateTime());
        users.setUpdateTime(TimeUtitl.dateTime());

        ResultFormat insert = usersService.saveUsers(users);

        if (insert.getCode() == 200) {
            logger.info("添加成功");
            return ResultUtil.success();
        }
        if (insert.getCode() == 101) {
            logger.info("用户名已存在");
            return ResultUtil.error(insert.getCode(), insert.getMsg());
        }

        return ResultUtil.error(100, "添加失败");
    }


    /**
     * 修改用户信息
     *
     * @param users
     * @return
     */
    @ApiOperation("修改用户信息接口")
    @PutMapping("/update")
    @ResponseBody
    public ResultFormat updatePgSorts(Users users) {

        users.getRegisterTime();
        users.setUpdateTime(TimeUtitl.dateTime());

        ResultFormat insert = usersService.saveUsers(users);

        if (insert.getCode() == 200) {
            logger.info("修改成功");
            return ResultUtil.success();
        }
        if (insert.getCode() == 101) {
            logger.info("用户名已存在");
            return ResultUtil.error(insert.getCode(), insert.getMsg());
        }

        return ResultUtil.error(100, "修改失败");

    }


    /**
     * 修改用户状态
     *
     * @param users
     * @return
     */
    @ApiOperation("修改用户状态接口")
    @PutMapping("/delete")
    public ResultFormat deletePgSorts(Users users) {

        logger.info("users=={}", users);

        boolean flag = usersService.updateById(users);

        if (flag) {
            logger.info("修改成功");
            return ResultUtil.success();
        } else {
            logger.info("修改失败");
            return ResultUtil.error(100, "修改失败");
        }
    }


}

 

6.application.yml

# 服务器端口
server:
  port: 8888

# Spring Boot 的数据源配置
spring:
  redis:
    database: 0
    host: localhost         # Redis服务器地址
    port: 6379              # Redis服务器连接端口
    password:              # Redis服务器连接密码(默认为空)
    pool:
      max-active: 200       # 连接池最大连接数(使用负值表示没有限制)
      max-idle: 10            # 连接池中的最大空闲连接
      max-wait: -1          # 连接池最大阻塞等待时间(使用负值表示没有限制)
      min-idle: 0           # 连接池中的最小空闲连接
    timeout: 1000         # 连接超时时间(毫秒)
  datasource:
    url: jdbc:mysql://localhost:3306/use_redis?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    maxOpenPreparedStatements: 20


mybatis-plus:
  # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
  mapper-locations: classpath:mapper/*.xml
  global-config:
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 1
  configuration:
    # 是否将sql打印到控制面板(该配置会将sql语句和查询的结果都打印到控制台)
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

# PageHelper分页插件
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

 

ajax的代码就不放出来了哈,各有各的写法。

 

这里使用是layui实现界面的

效果图如下:

 

首页

 

 

 

添加页面

 

 

 

修改页面

 

 

 

Api文档

 

项目已托管码云

地址:https://gitee.com/ckfeng/springboot_mysql_redis.git

 

    待更新....

 


原文链接:https://www.cnblogs.com/ckfeng/p/12818705.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:LeetCode 面试题14- I. 剪绳子

下一篇:Java阻塞队列四组API介绍