Springboot2整合ehcache缓存笔记整理

参考Springboot整合ehcache缓存

EhCache是一个比较成熟的 Java缓存框架,最早从 hibernate发展而来, 是进程中的缓存系统,它提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的 cache管理方案,快速简单。

Springbootehcache的使用非常支持,所以在 Springboot中只需做些配置就可使用,且使用方式也简易。

1. pom.xml中添加依赖


            org.springframework.boot
            spring-boot-starter-cache

            net.sf.ehcache
            ehcache

完整的 pom.xml如下


    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.3.5.RELEASE

    com.roncoo.eshop
    cache
    0.0.1-SNAPSHOT
    cache
    Demo project for Spring Boot

        5.2.10.RELEASE
        UTF-8
        1.8

            org.springframework.boot
            spring-boot-starter-web

            org.projectlombok
            lombok
            1.18.10
            provided

            org.springframework.boot
            spring-boot-starter-cache

            net.sf.ehcache
            ehcache

            org.springframework.boot
            spring-boot-starter-test
            test

                    org.junit.vintage
                    junit-vintage-engine

                org.springframework.boot
                spring-boot-maven-plugin

2. 创建ehcache.xml配置文件

位置: classpath目录下,即 src/main/resources/ehcache.xml

Springboot2整合ehcache缓存笔记整理

3. 在application.yml中加入以下配置代码

spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

4. 在启动类前加上@EnableCaching注解;这样的话,启动类启动时会去启动缓存启动器

@SpringBootApplication
@EnableCaching
public class CacheApplication {

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

}

至此 ehcacheSpringboot中就配置完成,下面编写测试代码

5. 实体类实现可序列化接口Serializable;由于需要实体类支持缓存中的磁盘存储,所以需要实体类实现可序列化接口

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 商品信息
 *
 * @author Administrator
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductInfo implements Serializable {

    private Long id;
    private String name;
    private Double price;
}

6. 使用@CachePut存数据到缓存使用@Cacheable读取缓存

import com.roncoo.eshop.cache.model.ProductInfo;

/**
 * 缓存service接口
 * @author Administrator
 *
 */
public interface CacheService {

    /**
     * 将商品信息保存到本地缓存中
     * @param productInfo
     * @return
     */
    public ProductInfo saveLocalCache(ProductInfo productInfo);

    /**
     * 从本地缓存中获取商品信息
     * @param id
     * @return
     */
    public ProductInfo getLocalCache(Long id);

}
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.roncoo.eshop.cache.model.ProductInfo;
import com.roncoo.eshop.cache.service.CacheService;

/**
 * 缓存Service实现类
 *
 * @author Administrator
 */
@Service
public class CacheServiceImpl implements CacheService {

    public static final String CACHE_NAME = "local";

    /**
     * 将商品信息保存到本地缓存中
     *
     * @param productInfo
     * @return
     */
    @CachePut(value = CACHE_NAME, key = "'key_'+#productInfo.getId()")
    public ProductInfo saveLocalCache(ProductInfo productInfo) {
        return productInfo;
    }

    /**
     * 从本地缓存中获取商品信息
     *
     * @param id
     * @return
     */
    @Cacheable(value = CACHE_NAME, key = "'key_'+#id")
    public ProductInfo getLocalCache(Long id) {
        return null;
    }

}

7. 编写控制器代码

import com.roncoo.eshop.cache.model.ProductInfo;
import com.roncoo.eshop.cache.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 缓存Controller
 *
 * @author Administrator
 */
@RestController
public class CacheController {

    @Autowired
    private CacheService cacheService;

    @PostMapping("/testPutCache")
    public String testPutCache(@RequestBody ProductInfo productInfo) {
        cacheService.saveLocalCache(productInfo);
        return "success";
    }

    @GetMapping("/testGetCache")
    public ProductInfo testGetCache(Long id) {
        return cacheService.getLocalCache(id);
    }

}

8. 测试

Springboot2整合ehcache缓存笔记整理

Springboot2整合ehcache缓存笔记整理

补充

// 使用@CacheEvict清除缓存
@CacheEvict(value="users",allEntries=true)
public void saveUsers(Users users) {
    this.usersRepository.save(users);
}
// @CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。
// 其中value、key和condition的语义与@Cacheable对应的属性类似;allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。
// 当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率

// 使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。

// @Cacheable:类或者方法上,类代表所有的方法都使用它,方法上针对特定的方法,作用就是先查询缓存是否有值,有的话就直接返回缓存结果

Original: https://www.cnblogs.com/ifme/p/13930160.html
Author: if年少有为
Title: Springboot2整合ehcache缓存笔记整理

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/541053/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球