《Spring Boot應(yīng)用緩存實(shí)踐之:Ehcache加持》

在如今高并發(fā)的互聯(lián)網(wǎng)應(yīng)用中,緩存的地位舉足輕重,對提升程序性能幫助不小。而3.x開始的 Spring也引入了對 Cache的支持,那對于如今發(fā)展得如火如荼的 Spring Boot來說自然也是支持緩存特性的。當(dāng)然 Spring Boot默認(rèn)使用的是 SimpleCacheConfiguration,即使用ConcurrentMapCacheManager 來實(shí)現(xiàn)的緩存。但本文將講述如何將 Ehcache緩存應(yīng)用到Spring Boot應(yīng)用中。

「Ehcache」 是一個基于Java實(shí)現(xiàn)的開源緩存管理庫,提供了用內(nèi)存、磁盤文件存儲、以及分布式存儲等多種靈活的管理方案。使用方式和原理都有點(diǎn)類似于 Spring事務(wù)管理,配合各項(xiàng)注解可以很容易的上手。

下文就上手來摸一摸它,結(jié)合對數(shù)據(jù)庫的操作,我們讓 Ehcache作為本地緩存來看一下效果!


準(zhǔn)備工作

  • 準(zhǔn)備好數(shù)據(jù)庫和數(shù)據(jù)表并插入相應(yīng)的數(shù)據(jù)(MySQL)

比如我這里準(zhǔn)備了一張用戶表,包含幾條記錄:

準(zhǔn)備好MySQL數(shù)據(jù)庫和數(shù)據(jù)表

我們將通過模擬數(shù)據(jù)庫的存取操作來看看 Ehcache緩存加入后的效果。


搭建工程:Springboot + MyBatis + MySQL + Ehcache

pom.xml 中添加如下依賴:

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

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

        <!--for mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

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

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

        <!--for ehcache-->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>

    </dependencies>

建立 Ehcache配置文件

創(chuàng)建Ehcache的配置文件 ehcache.xml并置于項(xiàng)目 classpath下:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>

    <diskStore path="java.io.tmpdir"/>

    <!-- 設(shè)定緩存的默認(rèn)數(shù)據(jù)過期策略 -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>

    <cache name="user"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="10"/>

</ehcache>

配置 application.properties

server.port=80

# Mysql 數(shù)據(jù)源配置
spring.datasource.url=jdbc:mysql://121.196.213.251:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=xxxxxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# mybatis 配置
mybatis.type-aliases-package=cn.carlos.springbt_ehcache.entity
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

# ehcache 配置
spring.cache.ehcache.config=classpath:ehcache.xml

編寫操作數(shù)據(jù)庫和 Ehcache緩存的業(yè)務(wù)代碼

  • 編寫entity
public class User {

    private Long userId;
    private String userName;
    private Integer userAge;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getUserAge() {
        return userAge;
    }

    public void setUserAge(Integer userAge) {
        this.userAge = userAge;
    }
}
  • 編寫mapper
public interface UserMapper {

    List<User> getUsers();

    int addUser(User user);

    List<User> getUsersByName( String userName );
}
  • 編寫service
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> getUsers() {
        return userMapper.getUsers();
    }

    public int addUser( User user ) {
        return userMapper.addUser(user);
    }

    @Cacheable(value = "user", key = "#userName")
    public List<User> getUsersByName( String userName ) {
        List<User> users = userMapper.getUsersByName( userName );
        System.out.println( "從數(shù)據(jù)庫讀取,而非讀取緩存!" );
        return users;
    }
}

看得很明白了,我們在 getUsersByName接口上添加了注解:@Cacheable。這是 Ehcache的使用注解之一,除此之外常用的還有 @CachePut@CacheEvit,分別簡單介紹一下:

  1. @Cacheable:配置在 getUsersByName方法上表示其返回值將被加入緩存。同時在查詢時,會先從緩存中獲取,若不存在才再發(fā)起對數(shù)據(jù)庫的訪問
  2. @CachePut:配置于方法上時,能夠根據(jù)參數(shù)定義條件來進(jìn)行緩存,其與 @Cacheable不同的是使用 @CachePut標(biāo)注的方法在執(zhí)行前不會去檢查緩存中是否存在之前執(zhí)行過的結(jié)果,而是每次都會執(zhí)行該方法,并將執(zhí)行結(jié)果以鍵值對的形式存入指定的緩存中,所以主要用于數(shù)據(jù)新增和修改操作上
  3. @CacheEvict:配置于方法上時,表示從緩存中移除相應(yīng)數(shù)據(jù)。
  • 編寫controller
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    CacheManager cacheManager;

    @GetMapping("/users")
    public List<User> getUsers() {
        return userService.getUsers();
    }

    @GetMapping("/adduser")
    public int addSser() {
        User user = new User();
        user.setUserId(4l);
        user.setUserName("趙四");
        user.setUserAge(38);
        return userService.addUser(user);
    }

    @RequestMapping( value = "/getusersbyname", method = RequestMethod.POST)
    public List<User> geUsersByName( @RequestBody User user ) {
        System.out.println( "-------------------------------------------" );
        System.out.println("call /getusersbyname");
        System.out.println(cacheManager.toString());
        List<User> users = userService.getUsersByName( user.getUserName() );
        return users;
    }

}

改造SpringBoot應(yīng)用主類

主要是在啟動類上通過 @EnableCaching注解來顯式地開啟 Ehcache緩存

@SpringBootApplication
@MapperScan("cn.carlos.springbt_ehcache")
@EnableCaching
public class SpringbtEhcacheApplication {

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

最終完工的整個工程的結(jié)構(gòu)如下:

完整工程結(jié)構(gòu)

實(shí)際實(shí)驗(yàn)

通過多次向接口 localhost/getusersbynamePOST數(shù)據(jù)來觀察效果:

interfaceData.png

可以看到緩存的啟用和失效時的效果(上文ehcache的配置文件中設(shè)置了緩存user的實(shí)效時間為10s):

緩存的啟用和失效時的數(shù)據(jù)取數(shù)據(jù)效果

后 記

由于能力有限,若有錯誤或者不當(dāng)之處,還請大家批評指正,一起學(xué)習(xí)交流!


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容