SpringBoot整合ehcache缓存

60 篇文章 1 订阅
7 篇文章 0 订阅
  • 导入依赖
<?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>

    <!-- springboot父类工程 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>

    <groupId>com.spring.boot.data.jpa</groupId>
    <artifactId>07SpringbootdataJpa</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.7</java.version>
        <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
    </properties>
    <dependencies> <!-- springBoot 的启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- thymeleaf 的启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- spring-data-jpa 的启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- druid 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>

        <!-- 测试工具的启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <!-- Spring Boot 缓存支持启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!-- Ehcache 坐标 -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>


    </dependencies>
</project>

  • 配置application.properties文件(resources目录下)
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/059topic
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

spring.cache.ehcache.config=ehcache.xml

  • 配置自定义缓存策略ehcache.xml(resources目录下)
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <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>
    <!-- 自定义缓存策略,id命名为users -->
    <cache name="users"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

  • 创建对象
package com.pojo;


import javax.persistence.*;
import java.io.Serializable;

/**
 * @Author:CarlosXu
 * @Date:2019/8/10 0010
 * @Description:com.bjsxt.spring.boot.data.jpa
 */
@Entity
@Table(name = "users")
public class Users  implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "age")
    private Integer age;



    public Users() {
    }

    public Users(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

  • 创建jpa接口类实现对jdbc的操作
import com.bjsxt.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @Author:CarlosXu
 * @Date:2019/8/10 0010
 * @Description:com.bjsxt.dao
 */
public interface UsersJpaRepository01 extends JpaRepository<Users,Integer> {
}

  • 创建service
public interface UsersService {

    List<Users> findAllUsers();

    void insertUsers(Users users);
}

/**
 * @Author:CarlosXu
 * @Date:2019/8/10 0010
 * @Description:com.bjsxt.service.impl
 */
@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersJpaRepository01 usersJpaRepository01;

    @Override
    @Cacheable(value = "users")
    public List<Users> findAllUsers() {
        return this.usersJpaRepository01.findAll();
    }

    // @CacheEvict(value = "users",allEntries = true)
    //清除缓存中以 users 缓存策略缓存的对象
    @Override
    @CacheEvict(value = "users",allEntries = true)
    public void insertUsers(Users users) {
        this.usersJpaRepository01.save(users);
    }


}

  • 创建测试类
/**
 * @Author:CarlosXu
 * @Date:2019/8/10 0010
 * @Description:com.bjsxt.test
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {App.class})
public class UsersTest {

    @Autowired
    private UsersService usersService;

    @Test
    public void  test01(){
        List<Users> allUsers = usersService.findAllUsers();
        for (Users u:allUsers) {
            System.out.println(u);
        }
        Users users=new Users("虞姬",23);
        this.usersService.insertUsers(users);

        List<Users> allUsers2 = usersService.findAllUsers();
        for (Users u:allUsers2) {
            System.out.println(u);
        }
    }

}

  • 启动类
@SpringBootApplication
@EnableCaching
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);

    }
}

tips: @Cacheable(value = “users”):表示使用id为users的缓存策略
@CacheEvict(value = “users”,allEntries = true):表示清除缓存中以 users 缓存策略缓存的对象。多用于先修改之后再查询,避免出现数据存放在缓存中,修改之后再次查询值却没有变化的情况。
@EnableCaching:允许使用缓存策略

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值