前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot整合Ehcache

SpringBoot整合Ehcache

作者头像
用户4919348
发布2019-05-21 12:02:19
1.2K0
发布2019-05-21 12:02:19
举报
文章被收录于专栏:波波烤鸭

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

SpringBoot整合Ehcache

创建SpringBoot项目及依赖

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

代码语言:javascript
复制
<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

代码语言:javascript
复制
<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

代码语言:javascript
复制
# 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文件

代码语言:javascript
复制
/**
 * @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

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

业务层

代码语言:javascript
复制
public interface UserService {
    List<User> findUserAll();
    User findUserById(Integer id);
    Page<User> findUserByPage(Pageable pageable);
    void saveUsers(User users);
}
代码语言:javascript
复制
/**
 * @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);
    }
}

单元测试

代码语言:javascript
复制
@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());
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年05月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SpringBoot整合Ehcache
    • 创建SpringBoot项目及依赖
      • 添加相关配置
        • 添加pojo文件
          • Dao接口
            • 业务层
              • 单元测试
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档