1. 程式人生 > >第 20 講 SpringBoot整合Cache

第 20 講 SpringBoot整合Cache

第二十講 SpringBoot整合Cache

宣告式快取: Spring定義CacheManager和Cache介面用來統一不同的快取技術,例如:JCache,EhCache,Hazelcast,Guava,Redis等。在使用Spring整合Cache的時候,我們需要註冊實現CacheManager的Bean。

Spring Boot為我們自動配置了JCacheCacheConfiguration,EhCacheCacheConfiguration,HazelcastCacheCnfiguration,GuavaCacheConfiguration、RedisCacheConfiguration、SimpleCacheConfiguration。

預設使用ConcurrenMapCacheManager

在我們不使用其他第三方快取依賴的時候,Spring自動採用ConcurrenMapCacheManager

2.1 SpringBoot整合mybatis


create table `account` (
	`id` int (11),
	`name` varchar (60),
	`money` double 
); 
insert into `account` (`id`, `name`, `money`) values('1','李四','1');
insert into `account` (`id`, `name`, `money`
) values('2','王老五','5.6'); insert into `account` (`id`, `name`, `money`) values('3','張三','4');

application.yml

spring:
  datasource:
    driver-class-name : com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm
    username: root
    password: root
mybatis:
  type-aliases-package: com.springboot.cache
  mapper-locations
: classpath:mybatis/mapper/*.xml config-location: classpath:mybatis/config/mybatis-config.xml

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <typeAliases>
    </typeAliases>
</configuration>

2.2 pom.xml匯入依賴

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

2.3 entity層:Account.java

public class Account {

private Integer id;

private String name;

private Double money;
......

}

2.4 dao層 :AccountDao.java

package com.springboot.cache.dao;

import com.springboot.cache.entity.Account;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Description:
 * @CreateTime: 2018-10-17 21:11
 * @Version:v1.0
 */
@Repository
public interface AccountDao {

    List<Account> queryAll();

    Account queryAccountById(Integer id);


}

AccountMapper.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.springboot.cache.dao.AccountDao">

    <resultMap id="BaseResultMap" type="com.springboot.cache.entity.Account">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="money" property="money" jdbcType="DOUBLE"/>
    </resultMap>

    <sql id="Base_Column_List">
      id,name,money
    </sql>
    
    <select id="queryAccountById" resultMap="BaseResultMap">
        SELECT 
        <include refid="Base_Column_List"/>
        FROM account
        WHERE id = #{id,jdbcType=INTEGER}
    </select>

    <select id="queryAll" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM account
    </select>
</mapper>

2.5 service層:

IAccountService.java

package com.springboot.cache.service;

import com.springboot.cache.entity.Account;

import java.util.List;

/**
 * @Description:
 * @CreateTime: 2018-10-17 21:29
 * @Version:v1.0
 */
public interface IAccoutService {

    List<Account> queryAll();

    Account queryAccountById(Integer id);

    String queryBook(Integer num);
}

AccountServiceImpl.java

package com.springboot.cache.service.impl;

import com.springboot.cache.dao.AccountDao;
import com.springboot.cache.entity.Account;
import com.springboot.cache.service.IAccoutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Author: zrblog
 * @CreateTime: 2018-10-17 21:30
 * @Version:v1.0
 */
@Service
public class AccountService implements IAccoutService {
    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> queryAll() {
        return accountDao.queryAll();
    }

    @Override
    @Cacheable("queryAccountById")
    public Account queryAccountById(Integer id) {
        simulateSlowService();
        return accountDao.queryAccountById(id);
    }

    @Override
    @Cacheable("books")  /**開啟快取策略*/
    public String queryBook(Integer num) {
        simulateSlowService();
        return num + "-- > Some Book";
    }

     /**
      * @Description: 延時三秒
      * @Date: 2018/10/18 22:32
      * @Author: zr
      * @param null
      * @Return 
      */
    private void simulateSlowService() {
        try {
            long time = 3000L;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}

2.5 沒有開啟快取功能測試:

package com.springboot.cache;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.cache.entity.Account;
import com.springboot.cache.service.impl.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
@MapperScan(value = "com.springboot.cache.dao")
public class ApplicationTests {

    @Autowired
    private AccountService accountService;

	@Test
	public void contextLoads() {
	}

	@Test
    public void testMybatis() throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();

        List<Account> accounts = accountService.queryAll();

        System.out.println("result:"+mapper.writeValueAsString(accounts));
    }

     /**
      * @Description: 沒有開啟快取,每隔三秒列印一次記錄
      * @Date: 2018/10/17
      * @Author: zr
      * @param null
      * @Return 
      */
    @Test
    public void testCache() throws JsonProcessingException {
        printlnAccount(1);
        printlnAccount(2);
        printlnAccount(1);
        printlnAccount(1);
        printlnAccount(2);

    }

    private void printlnAccount(Integer id) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Account account = accountService.queryAccountById(id);
        String accountJson = mapper.writeValueAsString(account);
        System.out.println("Account--" +id+ "-->" + accountJson);
    }

2.6 開啟快取測試

2.6.1 添加註解@EnableCaching

a

2.6.2 需要快取的方法添加註解@Cacheable

b

2.6.3 測試,當快取有這個資料時,會直接返回資料,不會等待資料庫去查詢資料

c

只有前面兩個資料,程式等待了3秒,之後的資料瞬間列印在了控制檯上,這說明快取起了作用。