SpringBoot整合Ehcache

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 本文介绍下SpringBoot整合SpringDataJPA后加入缓存组件Ehcache的操作。


 本文介绍下SpringBoot整合SpringDataJPA后加入缓存组件Ehcache的操作。

SpringBoot整合Ehcache

创建SpringBoot项目及依赖

 创建一个SpringBoot项目,添加如下依赖。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.32</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.14</version>
    </dependency>
    <dependency>
        <groupId>error</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
</dependencies>

添加相关配置

 添加Ehcache的配置文件和application.properties

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <diskStore path="java.io.tmpdir"/>
    <!--defaultCache:echcache 的默认缓存策略 -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <!-- 自定义缓存策略 -->
    <cache name="users"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

application.properties

# mysql 的相关连接信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# 关联Ehcache的配置文件
spring.cache.ehcache.cofnig=ehcache.xml

添加pojo文件

/**
 * @program: springboot-ehcache
 * @description: 用户对应的实体类
 * @author: 波波烤鸭
 * @create: 2019-05-17 11:22
 */
@Entity
@Table(name="users")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="userid")
    private Integer userid;
    @Column(name="username")
    private String username;
    @Column(name="userage")
    private Integer userage;
    public Integer getUserid() {
        return userid;
    }
    public void setUserid(Integer 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;
    }
    @Override
    public String toString() {
        return "User{" +
                "userid=" + userid +
                ", username='" + username + '\'' +
                ", userage=" + userage +
                '}';
    }
}

Dao接口

 创建Dao接口并继承JpaRepository

/**
 * @program: springboot-ehcache
 * @description: 持久层实现Jpa
 * @author: 波波烤鸭
 * @create: 2019-05-17 11:25
 */
public interface UsersRepository extends JpaRepository<User,Integer> {
}

业务层

public interface UserService {
    List<User> findUserAll();
    User findUserById(Integer id);
    Page<User> findUserByPage(Pageable pageable);
    void saveUsers(User users);
}
/**
 * @program: springboot-ehcache
 * @description: 业务层实现类
 * @author: 波波烤鸭
 * @create: 2019-05-17 11:27
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UsersRepository usersRepository;
    @Override
    @Cacheable(value="users")
    public List<User> findUserAll() {
        return this.usersRepository.findAll();
    }
    @Override
    //@Cacheable:对当前查询的对象做缓存处理
    @Cacheable(value="users")
    public User findUserById(Integer id) {
        return this.usersRepository.findById(id).get();
    }
    @Override
    @Cacheable(value="users",key="#pageable.pageSize")
    public Page<User> findUserByPage(Pageable pageable) {
        return this.usersRepository.findAll(pageable);
    }
    @Override
    //@CacheEvict(value="users",allEntries=true) 清除缓存中以users缓存策略缓存的对象
    @CacheEvict(value="users",allEntries=true)
    public void saveUsers(User users) {
        this.usersRepository.save(users);
    }
}

单元测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringbootEhcacheApplication.class})
public class SpringbootEhcacheApplicationTests {
    @Resource
    private UserService userService;
    @Test
    //@Transactional
    //@Rollback(false)//取消自动回滚
    public void contextLoads() {
        //第一次查询
        System.out.println(this.userService.findUserById(6));
        //第二次查询
        System.out.println(this.userService.findUserById(6));
    }
    @Test
    public void testFindUserByPage(){
        Pageable pageable = new PageRequest(0, 2);
        //第一次查询
        System.out.println(this.userService.findUserByPage(pageable).getTotalElements());
        //第二次查询
        System.out.println(this.userService.findUserByPage(pageable).getTotalElements());
        //第三次查询
        pageable = new PageRequest(1, 2);
        System.out.println(this.userService.findUserByPage(pageable).getTotalElements());
    }
    @Test
    public void testFindAll(){
        //第一次查询
        System.out.println(this.userService.findUserAll().size());
        User users = new User();
        users.setUsername("bobo kaoya");
        users.setUserage(22);
        this.userService.saveUsers(users);
        //第二次查询
        System.out.println(this.userService.findUserAll().size());
    }
}


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
7月前
|
存储 缓存 Java
SpringBoot整合EhCache
SpringBoot默认情况下是整合了EhCache的,但是默认整合的EhCache的2.x版本,本文依然整合EhCache的3.x版本。
55 0
|
10月前
|
XML 缓存 Java
|
存储 缓存 Java
EhCache-配置和SpringBoot整合
EhCache-配置和SpringBoot整合
EhCache-配置和SpringBoot整合
|
存储 缓存 NoSQL
SpringBoot整合Ehcache缓存(二十二)
一.Ehcache 二. SpringBoot 整合 Ehcache 缓存 二.一 添加 ehcache依赖 二.二 配置 ehcache.xml 文件 二.三 application.yml 指定 ehcache缓存配置文件位置 二.四 启动类添加 @EnableCaching 缓存 二.五 Spring Cache 注解与 Ehcache的使用
462 0
|
XML 缓存 Java
解释SpringBoot之Ehcache 2.x缓存
这里介绍Ehcache 2.X 缓存
1058 0
|
Web App开发 缓存 Java
SpringBoot学习:整合shiro(身份认证和权限认证),使用EhCache缓存
项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 (一)在pom.xml中添加依赖:   [html] view plain copy          1.
3199 0
|
14天前
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源
|
22天前
|
Java API Spring
SpringBoot项目调用HTTP接口5种方式你了解多少?
SpringBoot项目调用HTTP接口5种方式你了解多少?
71 2
|
22天前
|
前端开发 JavaScript Java
6个SpringBoot 项目拿来就可以学习项目经验接私活
6个SpringBoot 项目拿来就可以学习项目经验接私活
33 0