springBoot2.0 配置 mybatis+mybatisPlus+redis

一.Idea新建springBoot项目

springBoot2.0 配置 mybatis+mybatisPlus+redis_第1张图片

springBoot2.0 配置 mybatis+mybatisPlus+redis_第2张图片

springBoot2.0 配置 mybatis+mybatisPlus+redis_第3张图片

springBoot2.0 配置 mybatis+mybatisPlus+redis_第4张图片

springBoot2.0 配置 mybatis+mybatisPlus+redis_第5张图片

next到完成,然后修改使用自己的maven

springBoot2.0 配置 mybatis+mybatisPlus+redis_第6张图片

等待下载包

二.pom.xml文件

xml version="1.0" encoding="UTF-8"?>
<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>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.3.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.examplegroupId>
    <artifactId>demo2artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>demo2name>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    
    <profiles>
        <profile>
            <id>devid>
            <properties>
                <profiles.active>devprofiles.active>
            properties>
            
            <activation>
                <activeByDefault>trueactiveByDefault>
            activation>
        profile>
        <profile>
            <id>prodid>
            <properties>
                <profiles.active>prodprofiles.active>
            properties>
        profile>
    profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.0.0version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.0.7.1version>
        dependency>

        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.3.2version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

三.application配置文件

application.properties 修改为 application.yml

新增application-dev.yml测试环境文件和application-prod.yml生成环境文件

application.yml配置

#默认配置文件
spring:
  profiles:
    active: @profiles.active@

#tomcat
server:
  port: 8080
  servlet:
    context-path: /demo2


#mybatis
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    jdbc-type-for-null: null
    auto-mapping-behavior: full
  mapper-locations: classpath*:mapping/*.xml
  type-aliases-package: com.sssr.assets.entity

#日志
logging:
  level:
    com.example.demo2.dao: debug
    org:
      springframework:
        boot:
          autoconfigure: ERROR
#日志文件输出路径
#  file:
#    assets.log

application-dev.yml配置

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/assets?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
      username: root
      password: 123456
      stat-view-servlet:
        url-pattern: /druid/*
        reset-enable: true
        login-username: druid
        login-password: druid
      web-stat-filter:
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
  #redis
  redis:
    database: 0
    host: localhost
    port: 6379
    timeout: 3000
    password:
jedis:
      #    链接池
      pool:
#       最大连接数(负值表示没有限制)
        max-active: 8
#       最大阻塞等待时间(负值表示没有限制)
        max-wait: 1
#       最大空闲链接
        max-idle: 8
#       最小空闲链接
        min-idle: 0

springBoot2.0 配置 mybatis+mybatisPlus+redis_第7张图片

四.entity,dao,controller,service,config,mapping包

springBoot2.0 配置 mybatis+mybatisPlus+redis_第8张图片

User.java 实体类

package com.example.demo2.entity;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * @author sssr
 * @version 1.0
 * @Description:
 * @date 2019/2/16
 */
@Getter
@Setter
public class User implements Serializable {
    private Long id;
    private String username;
    private String password;

}

UserDao.java

package com.example.demo2.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo2.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author sssr
 * @version 1.0
 * @Description:
 * @date 2019/2/16
 */
@Repository
public interface UserDao extends BaseMapper {
    /**
     * 用户列表
     * @return
     */
    List getList();
}

UserDao.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.demo2.dao.UserDao">

    <resultMap id="userMap" type="com.example.demo2.entity.User">
    resultMap>

    <select id="getList" resultMap="userMap">
      SELECT u.* FROM user u
    select>
mapper>

UserService.java

package com.example.demo2.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo2.entity.User;

import java.util.List;

/**
 * @author sssr
 * @version 1.0
 * @Description:
 * @date 2019/2/16
 */
public interface UserService extends IService {

    List getList();
}

UserServiceImpl.java

package com.example.demo2.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo2.dao.UserDao;
import com.example.demo2.entity.User;
import com.example.demo2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author sssr
 * @version 1.0
 * @Description:
 * @date 2019/2/16
 */
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    /** (non-Javadoc)
     * @value:   在redis中 保存缓存在以user命名的集合中
     * @key  :   user集合中的关键字,注意字符串要以单引号括住  '',变量前缀加#号,如#userId
     */
    @Override
    @Cacheable(value="user",key="'userList'")
    public List getList() {
        return userDao.getList();
    }
}

UserController.java

package com.example.demo2.controller;

import com.example.demo2.entity.User;
import com.example.demo2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author sssr
 * @version 1.0
 * @Description:
 * @date 2019/2/16
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public List getUserList(){
        return userService.getList();
    }
}

 RedisConfig.java

package com.example.demo2.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.time.Duration;

/**
 * @author sssr
 * @version 1.0
 * @Description:
 * @date 2019/1/17
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    //缓存管理器
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template);//设置序列化工具
        template.afterPropertiesSet();
        return template;
    }
    private void setSerializer(StringRedisTemplate template){
        @SuppressWarnings({ "rawtypes", "unchecked" })
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
    }
}
Demo2Application.java
package com.sssr.assets;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @author sssr
 * 配置redis缓存,允许缓存
 *@EnableScheduling
 *@EnableCaching
 */
@SpringBootApplication
@EnableScheduling
@EnableCaching
@MapperScan({"com.example.demo2.dao","com.baomidou.mybatisplus.samples.quickstart.mapper"})
public class AssetsApplication {

   public static void main(String[] args) {
      SpringApplication.run(AssetsApplication.class, args);
   }

}

 

最终结构

springBoot2.0 配置 mybatis+mybatisPlus+redis_第9张图片

五.运行测试

springBoot2.0 配置 mybatis+mybatisPlus+redis_第10张图片

 

转载于:https://www.cnblogs.com/qq1272850043/p/10388212.html

你可能感兴趣的:(springBoot2.0 配置 mybatis+mybatisPlus+redis)