spring boot + mysql +mybatis +redis(二級緩存)實例

配置了好幾天纔算配置好

個人感覺spring boot版本間兼容不好

一、創建maven項目並添加 pom 依賴

<?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.0</modelVersion>
    <groupId>1</groupId>
    <artifactId>1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <!--項目編碼格式以及JDK版本指定-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>


    <!-- Add typical dependencies for a web application -->

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

        <!--alibaba.fastjson-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.41</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

        //spring 包 很容易與spring boot 版本衝突 注意
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>




    </dependencies>

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



</project>


二、yml 配置文件

################################
######                     #####
######     應用通用配置     #####
######                     #####
################################

spring:
# 應用名稱
  application:
    name: MavenDemoProject

# 多環境配置
  profiles:
    active: dev

# http請求編碼配置
  http:
    encoding:
      charset: UTF-8
      force: true
      enabled: true

# mysql數據庫配置
  datasource:
#    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    #url,username,password動態配置
    url: jdbc:mysql://localhost:3306/test?useUnicode:true&characterEncoding:utf-8
    username: root
    password: ****
    dbcp2:
       #最大空閒連接
       max-idle: 100
       #最小空閒連接
       min-idle: 10
       #最大連接數
       max-total: 200
       #最大等待時間
       max-wait-millis: 5000
       #檢測週期 單位毫秒
       time-between-eviction-runs-millis: 30000
       #連接池足校生存時間
       min-evictable-idle-time-millis: 1800000
#       test-on-borrow: true
#       validation-query: SELECT 1
#       test-while-idle: true
#       num-tests-per-eviction-run: 100


# redis緩存配置
  redis:
     #host,password,port,database動態配置
    host: *******
    password: *****
    port: 6379
    database: 0
    timeout: 2000
    pool:
        # 連接池中的最大空閒連接
        max-idle: 80
        # 連接池中的最小空閒連接
        min-idle: 1
        # 連接池最大連接數(使用負值表示沒有限制)
        max-active: 80
        # 連接池最大阻塞等待時間(使用負值表示沒有限制)
        max-wait: 10

# mybatis配置
mybatis:
  #config-location: classpath:/mybatis-config.xml
  type-aliases-package: com.frank.dao.*
  mapper-locations: classpath:/mapper/*.xml
#  configuration:
#    #延時加載
#    lazy-loading-enabled: true
#    map-underscore-to-camel-case: true
#    use-column-label: true

需要在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.weixin.dao.student.StudentMapper">
    <!--開啓二級緩存-->
<cache type="com.weixin.config.RedisConfig"/>
    <select id="get" resultType="com.weixin.model.Student">

        SELECT * FROM student

        WHERE id = #{id}

    </select>

    <update id="update" parameterType="com.weixin.model.Student">

        UPDATE student SET

        name = #{name},

        age = #{age}

        WHERE id = #{id}

    </update>

</mapper>

bean類型 需要實現Serializable接口

package com.weixin.model;

import java.io.Serializable;

public class Student implements Serializable {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

三、Redis 配置類

package com.weixin.config;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisConfig implements Cache {
    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(RedisConfig.class);

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private  String id; // cache instance id
    private RedisTemplate redisTemplate;
    private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis過期時間
    private static final String DEFAULT_ID = "default_id";


    public RedisConfig(String id) {
        if (id == null) {
            id = DEFAULT_ID;
        }
        this.id = id;
    }



    public void setId(String id ){

        this.id = id;
    }
    @Override
    public String getId() {
        return id;
    }

    /**
     * Put query result to redis
     *
     * @param key
     * @param value
     */
    @Override
    @SuppressWarnings("unchecked")
    public void putObject(Object key, Object value) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            ValueOperations opsForValue = redisTemplate.opsForValue();
            opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
            logger.debug("Put query result to redis");
        } catch (Throwable t) {
            logger.error("Redis put failed", t);
        }
    }

    /**
     * Get cached query result from redis
     *
     * @param key
     * @return
     */
    @Override
    public Object getObject(Object key) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            ValueOperations opsForValue = redisTemplate.opsForValue();
            logger.debug("Get cached query result from redis");
            return opsForValue.get(key);
        } catch (Throwable t) {
            logger.error("Redis get failed, fail over to db", t);
            return null;
        }
    }

    /**
     * Remove cached query result from redis
     *
     * @param key
     * @return
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object removeObject(Object key) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            redisTemplate.delete(key);
            logger.debug("Remove cached query result from redis");
        } catch (Throwable t) {
            logger.error("Redis remove failed", t);
        }
        return null;
    }

    /**
     * Clears this cache instance
     */
    @Override
    public void clear() {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
        logger.debug("Clear all the cached query result from redis");
    }

    /**
     * This method is not used
     *
     * @return
     */
    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        //spring-data-redis的RedisTemplate<K, V>模板類在操作redis時默認使用JdkSerializationRedisSerializer來進行序列化
        //一下修改爲String類型序列化 解決redis庫中 K V 出現 xAC\xED\x00\x05t\x00\x04 問題
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
//        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
//        redisTemplate.setHashValueSerializer(stringSerializer);

        return redisTemplate;
    }
}

ApplicationContextHolder 類

package com.weixin.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        applicationContext = ctx;
    }

    /**
     * Get application context from everywhere
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * Get bean by class
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * Get bean by class name
     *
     * @param name
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }
}

上面需要用到spring-context jar 包,需要注意版本,版本不同可能衝突

注意:

 RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
//        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
//        redisTemplate.setHashValueSerializer(stringSerializer);

上面表示redis中的key值設置爲String類型,這樣能更清楚的找到key值,但是如果開啓二級緩存的話,執行sql語句時查找的對象不會進行redis存儲,因爲查找到對象key爲Object值,控制檯會報錯,如圖

這裏寫圖片描述

可以改成 key.toString() 進行存儲,但是出現文件分級,如圖:

這裏寫圖片描述

所以說還要按照實際情況進行設置

四、controller層進行使用

package com.weixin.controller;

import com.alibaba.fastjson.JSONObject;
import com.weixin.config.RedisConfig;
import com.weixin.model.Student;
import com.weixin.service.student.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class SpringBootTest {

    @Autowired
    private StudentService studentService;


    @RequestMapping("/one")
    public JSONObject test() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "success");
        //id 沒有實際價值 只是爲了更好確認
        RedisConfig redisConfig = new RedisConfig("100");
        redisConfig.putObject("1000","hello i m frank!");

        return jsonObject;
    }

    /**
     * 根據id獲取對象
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public JSONObject get(@PathVariable("id") int id) {

        Student student = studentService.get(id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", student.getId());
        jsonObject.put("age", student.getAge());
        jsonObject.put("name", student.getName());
        RedisConfig redisConfig = new RedisConfig("100");
        redisConfig.putObject("frank",jsonObject);
        return jsonObject;

    }

    /**
     * 更新對象
     *
     * @return
     */
    @RequestMapping("/update")
    public String put() {

        Student student = new Student();
        student.setId(1);
        student.setAge(22);
        student.setName("new frank");
        studentService.update(student);

        return "success";

    }

    @RequestMapping("/getRedis")

    public JSONObject get() {

        RedisConfig redisConfig = new RedisConfig("100");

        return  (JSONObject) redisConfig.getObject("frank");

    }
}

五、運行查看

這裏寫圖片描述

查看redis

這裏寫圖片描述

添加JSON value 值

這裏寫圖片描述

顯示情況

這裏寫圖片描述

如果想顯示String的話 可以在RedisConfig中 setValueSerializer 進行設置

獲取value值

這裏寫圖片描述

五、項目總體結構

這裏寫圖片描述

項目下載

http://download.csdn.net/download/jasonhector/10158450

發佈了65 篇原創文章 · 獲贊 71 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章