springboot+mybatis+swagger+redis+mysql搭建的第一个项目

技术

springboot集成mybatis
maven mysql数据库
redis做缓冲
druid数据库连接池
ConcurrentHashMap在线程安全的基础上提供了更好的写并发能力
集成Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件
springboot+redis+mybatis+mysql+swagger+定时器
需要注意的地方:

1.本项目是基于eclipse开发工具开发的

2.sql文件放到根目录下的sql文件中

3.项目中用到了redis做缓冲作用,我将redis的压缩包放到了redis文件夹中。只需要安装到本地。启动redis。启动项目

4.用到了springboot提供的定时器功能,每隔一分钟会定时清空所有redis数据

5.swagger很好用。可以测试接口功能

6.启动后项目的访问路径是:http://localhost:8082/swagger-ui.html

该项目很适用于新手学习springboot的相关知识。本人也是一位springboot的初学者

本项目使用的环境:

开发工具:eclipse
jdk:1.8
maven:3.3.9

1. 创建项目
第一步首先需要创建项目,这里就不多介绍了。项目的结构如下图:
springboot+mybatis+swagger+redis+mysql搭建的第一个项目_第1张图片
2 配置文件
下面是application.properties的配置文件,也是springboot默认加载的配置文件

#数据源驱动
jdbc.ds.url=jdbc:mysql://localhost/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.ds.username=root
jdbc.ds.password=root
jdbc.ds.driver-class-name=com.mysql.jdbc.Driver


server.port=8081

#mybatis配置    
mybatis.type-aliases-package=com.westlife.*.model
mybatis.mapper-locations=classpath:mapper/*.xml

1  # REDIS 配置信息
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=  
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8  
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)
spring.redis.timeout=5000 


#日志相关配置  
#:logging.level.root相当于以往spring配置log4j.xml中的root级别 
logging.level.root=INFO  
#logging.org.springFramework.web具体服务的日志级别
logging.level.org.springframework.web=DEBUG  
logging.level.org.mybatis=ERROR
#logging.path:日志的输出路径
#logging.path=log\myspringboot.log
#logging.file:输出的日志文件
logging.file=logs/myspringboot.log

3. pom.xml文件需要的依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>com.westlife.demogroupId>
    <artifactId>demo-boot-ssmartifactId>
    <version>0.0.1-SNAPSHOTversion>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.1.RELEASEversion>
    parent>

    <properties>
        <webVersion>3.1webVersion>
    properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
       
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-loggingartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
            <exclusions>
                <exclusion>
                    <artifactId>log4j-over-slf4jartifactId>
                    <groupId>org.slf4jgroupId>
                exclusion>
                <exclusion>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-starter-tomcatartifactId>
                exclusion>
            exclusions>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-tomcatartifactId>
            <scope>providedscope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>

        

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.2.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.11version>
        dependency>

        
        <dependency>
            <groupId>org.apache.tomcat.embedgroupId>
            <artifactId>tomcat-embed-jasperartifactId>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.2.2version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.2.2version>
        dependency>

    dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-pluginartifactId>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
    build>
project>

4. 实体类user

package com.westlife.demo.model;

import java.io.Serializable;

import org.hibernate.validator.constraints.NotEmpty;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "用户信息", description = "用户信息")
public class User implements Serializable{
    private static final long serialVersionUID = 1492973623389075081L;
    @NotEmpty(message="id不能为空!!!")
    private Integer id;

    @NotEmpty(message="username不能为空!!!")
    private String username;

    @NotEmpty(message="password不能为空!!!")
    private String password;

    @NotEmpty(message="email不能为空!!!")
    private String email;

    /**
     * 是否可用(0禁用,1可用)
     */
    @NotEmpty(message="useable不能为空!!!")
    private Integer useable;

    /**
     * 创建时间
     */
    @NotEmpty(message="addtime不能为空!!!")
    private String addtime;

    /**
     * 登陆时间
     */
    @NotEmpty(message="logintime不能为空!!!")
    private String logintime;

    /**
     * 登陆IP
     */
    @NotEmpty(message="loginip不能为空!!!")
    private String loginip;

    /**
     * @return id
     */
    @ApiModelProperty("唯一id")
    public Integer getId() {
        return id;
    }

    /**
     * @param id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return username
     */
    @ApiModelProperty("用户名称")
    public String getUsername() {
        return username;
    }

    /**
     * @param username
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return password
     */
    @ApiModelProperty("登陆密码")
    public String getPassword() {
        return password;
    }

    /**
     * @param password
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return email
     */
    @ApiModelProperty("邮箱")
    public String getEmail() {
        return email;
    }

    /**
     * @param email
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * 获取是否可用(0禁用,1可用)
     *
     * @return useable - 是否可用(0禁用,1可用)
     */
    @ApiModelProperty("状态是否可用(0禁用,1可用)")
    public Integer getUseable() {
        return useable;
    }

    /**
     * 设置是否可用(0禁用,1可用)
     *
     * @param useable 是否可用(0禁用,1可用)
     */
    public void setUseable(Integer useable) {
        this.useable = useable;
    }

    /**
     * 获取创建时间
     *
     * @return addtime - 创建时间
     */
    @ApiModelProperty("创建时间")
    public String getAddtime() {
        return addtime;
    }

    /**
     * 设置创建时间
     *
     * @param addtime 创建时间
     */
    public void setAddtime(String addtime) {
        this.addtime = addtime;
    }

    /**
     * 获取登陆时间
     *
     * @return logintime - 登陆时间
     */
    @ApiModelProperty("登陆时间")
    public String getLogintime() {
        return logintime;
    }

    /**
     * 设置登陆时间
     *
     * @param logintime 登陆时间
     */
    public void setLogintime(String logintime) {
        this.logintime = logintime;
    }

    /**
     * 获取登陆IP
     *
     * @return loginip - 登陆IP
     */
    @ApiModelProperty("登陆Ip")
    public String getLoginip() {
        return loginip;
    }

    /**
     * 设置登陆IP
     *
     * @param loginip 登陆IP
     */
    public void setLoginip(String loginip) {
        this.loginip = loginip;
    }
}

5. UserMapper.java

package com.westlife.demo.mapper;

import java.util.List;

import com.westlife.demo.common.RequestUser;
import com.westlife.demo.model.User;

public interface UserMapper {

    List queryList();

    void save(RequestUser requestUser);

    void batchDelete(Integer[] ids);

    void update(RequestUser requestUser);

}

6. UserService.java

package com.westlife.demo.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.westlife.demo.common.AjaxResult;
import com.westlife.demo.common.RequestUser;
import com.westlife.demo.controller.UserController;
import com.westlife.demo.mapper.UserMapper;
import com.westlife.demo.model.User;

@Service
public class UserService {
    protected static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserMapper userMapper;

    public List queryList() {
        List list = userMapper.queryList();
        return list;
    }

    public AjaxResult save(RequestUser requestUser) {
        userMapper.save(requestUser);
        return new AjaxResult();
    }

    public AjaxResult batchDelete(Integer[] ids) {
        userMapper.batchDelete(ids);
        return new AjaxResult();
    }

    public AjaxResult update(RequestUser requestUser) {
        userMapper.update(requestUser);
        return new AjaxResult();
    }

}

7. UserMapper.xml



<mapper namespace="com.westlife.demo.mapper.UserMapper">
    <select id="queryList" resultType="com.westlife.demo.model.User">
        SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u
    select>

    <select id="queryById" resultType="com.westlife.demo.model.User">
        SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u where u.id = #{id}
    select>

    <insert id="save">
        insert into t_user(username, password, email, useable, addtime)
        values(#{username}, #{password}, #{email}, #{useable}, now())
    insert>

    <update id="update">
        update t_user set password = #{password}, email = #{email}, useable = #{useable} where id = #{id}
    update>

    <delete id="batchDelete">
        delete from t_user where id in
        <foreach collection="array" item="item" open="(" separator="," close=")">
            #{item}
        foreach>
    delete>

    
mapper>

8. UserController.java

package com.westlife.demo.controller;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/*import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;*/
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.westlife.demo.common.AjaxResult;
import com.westlife.demo.common.GeneralException;
import com.westlife.demo.common.RequestDto;
import com.westlife.demo.common.RequestUser;
import com.westlife.demo.model.User;
import com.westlife.demo.service.RedisService;
import com.westlife.demo.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

//@Controller
@Api(value = "测试Swagger2",description="简单的API")
@RestController
@EnableScheduling//定时任务的注解
public class UserController
{
    protected static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    private ConcurrentHashMap pool = new ConcurrentHashMap<>();

    @Autowired
    private RedisTemplate   redisTemplate;//注入redisService类

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisService redisService;

    @ApiOperation(value = "查询用户", notes = "根据所有用户") 
    @RequestMapping(value="/queryList", method = RequestMethod.POST)
    public List queryList(){
        List list=userService.queryList();
        pool.put("list", list);
        redisService.setObj("listRedis", list);
        pool.put("listMap", list);
        return list;
    }
    @ApiOperation(value = "查询ConcurrentHashMap的list缓存", notes = "缓存obj") 
    @RequestMapping(value="/queryMapList", method = RequestMethod.POST)
    public Object queryMapList(){

        return pool.get("listMap");//从缓存map中拿数据;
    }

    @ApiOperation(value = "查询Redis的list缓存", notes = "缓存obj") 
    @RequestMapping(value="/queryRedisList", method = RequestMethod.POST)
    public Object queryRedisList(){
        return redisService.getObj("listRedis");//从缓存redis中拿数据;
    }

    @ApiOperation(value = "添加用户", notes = "添加单个用户") 
    @RequestMapping(value="/addUser", method = RequestMethod.POST)
    public AjaxResult addUser(@RequestBody(required = true) @Valid RequestUser requestUser,
            BindingResult bindingResult) throws GeneralException{
        if (bindingResult.hasErrors()) {
            List fieldErrors = bindingResult.getFieldErrors();
            throw new GeneralException("5001", fieldErrors.get(0).getDefaultMessage());
        }
        AjaxResult ajaxResult=new AjaxResult();
        userService.save(requestUser);
        return ajaxResult;
    }


    @ApiOperation(value = "删除用户", notes = "删除多个用户") 
    @RequestMapping(value="/delUser", method = RequestMethod.POST)
    public AjaxResult delUser(@RequestBody(required = true) RequestDto requestDto){
        return userService.batchDelete(requestDto.getIds());
    }

    @ApiOperation(value = "更改用户", notes = "更改单个用户") 
    @RequestMapping(value="/updateUser", method = RequestMethod.POST)
    public AjaxResult updateUser(@RequestBody(required = true) @Valid RequestUser requestUser,
            BindingResult bindingResult) throws GeneralException{
        if (bindingResult.hasErrors()) {
            List fieldErrors = bindingResult.getFieldErrors();
            throw new GeneralException("5001", fieldErrors.get(0).getDefaultMessage());
        }
        return userService.update(requestUser);
    }

    // 每1分钟执行一次
        @Scheduled(cron = "0 0/1 * * * ? ")
        public void timer() {
            redisService.flushDB();//清空所有redis数据
        }
}
  1. springboot启动类 Application.java
package com.westlife.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;

import com.westlife.demo.controller.UserController;

/**
 * 
 * @author  westlife
 * @date 创建时间:2017年12月15日 下午4:32:07 
 * @version 1.0 
 * @parameter
 * springboot启动器
 */
// 开启缓存
@EnableCaching
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    protected static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        logger.info("SpringBoot开始加载");
        SpringApplication.run(Application.class, args);
        logger.info("SpringBoot加载完毕");
    }
}

10. 启动项目
1springboot+mybatis+swagger+redis+mysql搭建的第一个项目_第2张图片

2springboot+mybatis+swagger+redis+mysql搭建的第一个项目_第3张图片
当控制台出现下图的异常时
springboot+mybatis+swagger+redis+mysql搭建的第一个项目_第4张图片
是因为没有启动redis服务。我们在本地启动

  1. 启动redis
    springboot+mybatis+swagger+redis+mysql搭建的第一个项目_第5张图片

    12. 访问swagger
    地址:http://localhost:8081/swagger-ui.html
    springboot+mybatis+swagger+redis+mysql搭建的第一个项目_第6张图片

  2. 测试结果
    springboot+mybatis+swagger+redis+mysql搭建的第一个项目_第7张图片

最后附上我的git地址项目源码

看项目源码点击这里我的git源码地址

你可能感兴趣的:(springboot,springboot,redis,mysql,mybatis,maven)