SpringBoot 2.0.4 使用Ehcache作为Hibernate的二级缓存和系统缓存

springboot+jpa(hibernate配置redis为二级缓存) springboot2.1.4 基于springboot最新版本2.1.4.RELEASE,采用jpa为dao层框架,配置redis(redisson)为hibernate的二级缓存。 立即下载

本文基于springboot 2.0.4 使用ehcache作为Hibernate的二级缓存 以及系统缓存
额外需要用的是mysql数据库

由于springboot2.x和1.x差别较大 使用1.x可能会有错误
另外ehcache版本也会导致有不同的问题 本文默认使用了spring-boot-starter-cache里面的ehcache

首先 先看一下POM文件的配置

<?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>

<groupId>com.demo.mt</groupId>
<artifactId>ehcache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>ehcache</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</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-web</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
<!-- 数据库动态条件查询 -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
</dependency>
<!-- 集成ehcache需要的依赖-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<exclusions>
<exclusion>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
</exclusion>
</exclusions>
</dependency>

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

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

使用的时候遇到一个错误是

Caused by: net.sf.ehcache.CacheException: Another CacheManager with same name 'HIBERNATE_CACHE' already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.

这里是由于Ehcache新版本只能有一个CacheManager导致,新增一个ehcache配置文件提供给系统缓存
这里本来是新增了一个ehcache配置给hibernate 但是hibernate的配置项provider_configuration_file_resource_path似乎无效 可能是路径写的有问题 最终是修改了系统缓存文件路径解决了报错

这里是application.yml

spring:
  application:
    name: ehcache-demo
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/ehcachedb?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true
    username: root
    password: 123456
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      minimum-idle: 1
      maximum-pool-size: 100
      auto-commit: true
      idle-timeout: 30000
      pool-name: AdvZuulHikariCP
      max-lifetime: 1800000
      connection-timeout: 30000
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    properties:
      hibernate:
        format-sql: true
        cache:
          use_query_cache: true
          use_second_level_cache: true
          provider_configuration_file_resource_path: ehcache.xml
          region:
            factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
      javax:
        persistence:
          sharedCache:
            mode: ENABLE_SELECTIVE
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache/ehcache-spring.xml
server:
  port: 10001

hibernate使用的ehcache.xml

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

<ehcache name="HIBERNATE_CACHE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

    <!--
      指定二级缓存存放在磁盘上的位置,可以使用磁盘目录,也可以使用Java System Property目录,user.home是用户目录、user.dir是用户当前工作目录、java.io.tmpdir是默认临时文件路径
      -->
    <diskStore path="../cache/hibernate"/>


    <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
                              properties="jndiName=java:/TransactionManager" propertySeparator=";"/>




    <defaultCache
            maxEntriesLocalHeap="0"
            eternal="false"
            timeToIdleSeconds="1200"
            timeToLiveSeconds="1200">
        <!--<terracotta/>-->
    </defaultCache>
    <!--可以给每个实体类指定一个配置文件,通过name属性指定,要使用类的全名
        1. name:Cache的唯一标识。
        2. maxElementsInMemory:内存中最大缓存对象数。
        3. eternal:Element是否永久有效,一旦设置true,timeout将不起作用。
        4. timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
        5. timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大。
        6. overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中。
        7. maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大。
        8. memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理缓存中的内容。默认策略是LRU(最近最少使用),你也可以设置为FIFO(先进先出)或是LFU(较少使用)

        9. diskSpoolBufferSizeMB  : 这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
        10. maxEntriesLocalHeap堆内存中最大缓存对象数,0没有限制(必须设置)
        11. maxEntriesLocalDisk硬盘最大缓存个数

    -->
    <cache name="entityCache"
           maxEntriesLocalHeap="1000"
           maxEntriesLocalDisk="10000"
           eternal="false"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="10"
           timeToLiveSeconds="20"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>

    </cache>

    <cache name="org.hibernate.cache.internal.StandardQueryCache"
           maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
        <persistence strategy="localTempSwap"/>

    </cache>

    <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
           maxEntriesLocalHeap="5000" eternal="true">
        <persistence strategy="localTempSwap"/>

    </cache>

</ehcache>

系统使用的ehcache-spring.xml

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

<ehcache name="DEFAULT_CACHE" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">


    <diskStore path="../cache/default"/>

    <defaultCache
            maxEntriesLocalHeap="0"
            eternal="false"
            timeToIdleSeconds="1200"
            timeToLiveSeconds="1200">
        <!--<terracotta/>-->
    </defaultCache>


    <cache name="testCache"
           maxEntriesLocalHeap="1000"
           maxEntriesLocalDisk="10000"
           eternal="false"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="20"
           timeToLiveSeconds="20"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
        <cacheEventListenerFactory class="com.demo.mt.ehcache.config.ehcache.CustomerCacheEventListenerFactory"/>
    </cache>

</ehcache>

其中

<cacheEventListenerFactory class="com.demo.mt.ehcache.config.ehcache.CustomerCacheEventListenerFactory"/>

这一部分是可以不要的 自己实例化一个监听器可以方便做一些统计或者一些其他处理

首先是关于Hibernate的二级缓存

在主类上添加缓存注解@EnableCaching

@EnableCaching
@SpringBootApplication
public class EhcacheApplication {

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


}

在实体上加注解

@Data
@Entity
@Table(name = "role_tb")
@EqualsAndHashCode(callSuper = false)
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "entityCache")
public class RoleEntity extends BaseEntity<RoleEntity, Long> {

    protected String roleName;
}

这样就完成了hibernate的二级缓存配置
使用测试工具请求
GET http://localhost:10001/role/1
就可以测试缓存的效果了

前面用hibernate的二级缓存只能用于findById这类的请求 对于findAll则无效
不知道有没有其他什么配置

后来又使用了系统缓存
在controller层加了注解测试

package com.demo.mt.ehcache.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.mt.ehcache.entity.BaseEntity;
import com.demo.mt.ehcache.service.BaseService;
import com.demo.mt.ehcache.utils.ResultModel;
import com.github.wenhao.jpa.Specifications;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;

/**
 * BaseController
 *
 * @author MT.LUO
 * 2018/7/9 11:34
 * @Description:
 */
@Slf4j
@CacheConfig(cacheNames = "testCache")
public class BaseController<S extends BaseService<T, ID>, T extends BaseEntity<T, ID>, ID extends Serializable> {
    @Autowired
    protected S baseManager;

    @Autowired
    private MessageSource messageSource;

    @Cacheable(key = "#root.target + '_' + #p0 + '_' + #p1")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResultModel getList(@RequestParam int pageSize, @RequestParam int pageNumber) {
        log.info("BaseController list");
        Specification<T> specification = Specifications.<T>and().eq("deleted", false).build();

        if (pageSize > 0) {

            Pageable pageable = PageRequest.of(pageNumber, pageSize);
            Page<T> page = baseManager.findAll(specification, pageable);
            return ResultModel.ok(page);

        } else if (pageSize == -1) {
            return ResultModel.ok(baseManager.findAll());
        } else {
            List<T> entities = baseManager.findAll(specification);
            return ResultModel.ok(entities);
        }
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResultModel findOne(@PathVariable ID id) {
        return ResultModel.ok(baseManager.findOne(id));
    }
}

通过请求
GET http://localhost:10001/user/list?pageSize=10&pageNumber=0
可以测试缓存效果

这里贴出源码地址GITHUB

微信公众号不定时更新中
微信公众号:yingzi_code

EhCache_Hibernate二级缓存配置_详细 本人在做项目时用到了Hibernate的二级缓存,使用的是EhCache,结合本人自己的理解总结了如何在java web项目中配合Hibernate使用二级缓存,以提高程序的性能,附带需要的文件,参考的文件,和测试类以及说明。 立即下载

相关推荐

详解spring boot集成ehcache 2.x 用于hibernate二级缓存

本篇文章主要介绍了详解spring boot集成ehcache 2.x 用于hibernate二级缓存,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

spring boot集成ehcache 2.x 用于hibernate二级缓存

spring boot集成ehcache 2.x 用于hibernate二级缓存[TOC] 本文将介绍如何在spring boot中集成ehcache作为hibernate的二级缓存。各个框架版本如下 spring boot:1.4.3.RELEASE spring framework: 4.3.5.RELEASE hibernate:5.0.1.Final(spring-boot-sta

yiduyangyi的专栏 6179

Sipeed麦克风阵列板练习

麦克风阵列板 Maix Dock Sipeed

sunshinebigbig的博客 3844

SpringBoot2.X正确配置以及集成hibernate5正确姿势

个人认为本人是目前SpringBoot2.X集成hibernate5最全的写法,大家有什么意见建议欢迎评论。 本人前面配置以及代码使用图片展示,方便圈出注意点,图片中的代码将在文章结尾一一放出。 1.springboot2.x的application.yml的配置文件 注意点在于2.*相较于1.*项目名访问设置不一样了。还有session时间的设置方法,具体的可以看我的注释。 2.applica...

wt592376761的博客 1万+

SPH vs Lagrange网格混合建模实战:用LS-DYNA模拟弹丸穿孔效应

本文深入探讨了在LS-DYNA中运用SPH与Lagrange网格混合建模技术,高效模拟超高速碰撞下弹丸穿孔效应的实战方法。通过分析模型分区策略、耦合界面处理及关键参数设置,解决了传统方法在模拟大变形、材料断裂时的网格畸变或计算成本高昂问题,为相关工程仿真提供了兼顾精度与效率的解决方案。

weixin_29211309的博客 116

OSMDroid 切换地图不更新的问题

用OSMDroid加载Google地图的时候 需要有按钮切换不同图层的地图,如果发现调用了mMapView.setTileSource(ITileSource aTileSource)方法的时候发现地图View没有更新的话,可能是因为两个实例化TileSource对象其子类BitmapTileSourceBase这个类的aName成员变量值一样导致的地图在setTileSource出现不更新问题,...

godoge的博客 1044

【springBoot】springboot2.X 整合spring默认的缓存及其原理(下)

前言: 上篇博客【springBoot】springboot2.X 整合spring默认的缓存及其原理(上)主要讲解了缓存的原理以及@cacheable的用法,本篇博客补充一下其它缓存注解的用法 @cacheable 调用方法之前,先看有没有数据 @CachePut 先调用方法,然后将结果进行缓存 1、@CachePut 保证方法被调用,又更新缓存数据(执行完方法后,将方法的返回值放入缓存) 上面解释完,可能有人觉得那么这个注解有什么作用啊,每次都调用方法,也就是意味着每次都要调用数据库,缓存没有起到任何作

李光 未来科技 400

STM32L051低功耗模式下LPUART的使用

STM32L0系列低功耗UART配置代码清单及注释,大家可参考学习使用。

嵌入式工程师 2110

Hibernate二级缓存

Hibernate二级缓存配置

jingde528的博客 812

GPS-SDR-SIM使用详解

GPS-SDR-SIM 是一款开源工具,能够生成 GPS 基带信号数据流,这些数据流可通过软件定义无线电(SDR)平台(如 ADALM-Pluto、bladeRF、HackRF、USRP 等)转换为射频(RF)信号。简单来说,它能模拟 GPS 卫星信号,帮助开发者或爱好者测试 GPS 接收设备的性能,而无需依赖真实的卫星信号。

qq_35621280的博客 1253

A2A 协议详解:Agent Card 的设计与实现

Agent Card 是 Agent2Agent (A2A) 协议中实现智能体发现与互操作性的核心组件。本文将深入剖析 Agent Card 的设计理念、关键字段及其在智能体生态系统中的作用。我们将通过详细的 JSON Schema 解析和 Python SDK 示例,帮助您理解如何精确地定义和发布智能体能力,为构建可发现、可协作的 AI 智能体奠定基础。当您使用a2a.Agent类初始化一个智能体时,SDK 会根据您提供的参数(nameversion等)自动构建内部的 Agent Card 表示。

加入“Super Entity”,与全能开发团队共探AI智能体与数字人项目,开启前沿技术之旅。 1496

Springboot为啥要有第二级缓存

在递归创建其他依赖的组件前,会将未完成的组件作为放入ObjectFactory类的一个实现类里面,生成他的代理对象objectProxy,然后把这个ObjectFactory对象放入到二级缓存里面,通过调用getEarlyBeanReference来获取未完成的bean,如果这个对象没有被aop动态代理,就直接返回原来的对象,如果被aop代理过,就为这个对象生成代理对象,然后返回的就是代理对象。,只要获取到它的地址,然后赋值过来就行了,所以它是在一级缓存还是在二级缓存并不重要。

qwqgood的博客 2113

2024年电气工程师最新面试题及答案

1. **基本电气工程原理**:包括电流、电压、电阻、功率等基本概念。2. **欧姆定律**:V = IR,描述电压、电流和电阻之间的关系。42. **风力发电系统组成**:包括风力涡轮机、发电机、控制系统等。44. **智能电网技术**:包括自动化控制、通信技术、数据分析等。10. **减少EMI**:使用屏蔽、滤波、合理布线等方法。40. **光伏系统组成**:包括光伏板、逆变器、控制器等。48. **能量存储技术**:包括电池、超级电容器、飞轮等。

guo162308的博客 6585

Hibernate使用Ehcache二级缓存

在Spring Boot项目中使用Hibernate配合Ehcache作为二级缓存,需要以下几个步骤: 步骤1:引入相关依赖 在项目的pom.xml文件中添加Ehcache和Hibernate-Ehcache的支持。 <dependencies> <!-- Spring Data JPA --> <dependency> &lt...

年轻就是资本的专栏 1225

AI量化学习入门指南:从零开始掌握人工智能投资策略

量化投资:利用数学模型和计算机算法进行投资决策的方法算法交易:自动执行预定义交易规则的系统机器学习:让计算机从数据中学习并改进的技术回测:用历史数据检验交易策略表现的过程特征工程:将原始数据转化为模型可理解的输入过拟合:模型过度适应历史数据,导致未来表现不佳夏普比率:衡量单位风险所获得的超额收益AI量化投资不仅仅是技术的应用,更是一种理性、系统化的投资哲学。它不追求预测市场的每一个拐点,而是通过概率思维和风险管理,在不确定性的市场中寻找统计优势。

AGI×大数据,开启智能时代的认知跃迁;解码AGI,赋能数据驱动的智能革命。 1139

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

hibernate之二级缓存

1、ehcache 1.为什么需要缓存 因为每次取数据都要进数据库,我们可是通过缓存来提高程序的性能,因为读取数据库没有读取内存迅速 关系型数据库:数据与数据之间存在关系(联系)的数据库 mysql/Oracle、sqlserver 非关系型数据库:数据与数据之间是不存在关系的,key-value 1、基于文件存储的数据库:ehcache 2、基于内存存储的数据库:redis、memcache ...

南下在线的博客 139

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Springboot2集成Ehcache做分布式缓存

Ehcache是一款优秀的缓存中间件,具体介绍可查阅官网http://www.ehcache.org/。目前已经出到3.X版本,但主流的基于Ehcache的分布式缓存方案还是以2.X为主。 Ehcache作为分布式缓存经过测试存在以下两个问题: 1.作为Springboot缓存方案,即通过@Cacheable实现的缓存,只能缓存本地,无法实现分布式。 2.手动可以实现分布式缓存,但没有分布式...

qq_41754420的博客 1994

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Hibernate之二级缓存

1. 为什么需要缓存 拉高程序的性能 关系型数据库:数据与数据之间存在关系(联系)的数据库 mysql/Oracle、sqlserver 非关系型数据库:数据与数据之间是不存在关系的,key-value ①基于文件存储的数据库:ehcache ②基于内存存储的数据库:redis、memcache ③基于文档存储的数据库:mongodb 2. 什么样的数据需要缓存 经常使用但是很少被修改或根本不改的数据 数据字典 业务场景比如:耗时较高的统计分析sql、电话账单查询sql等 3...

小宝的宝呢的博客 244

为Spring集成的Hibernate配置二级缓存

前面我们已经集成了Spring4.2.5+Hibernate4.3.11+Struts1.3.8了,接下来我们就要为Spring4.2.5集成的Hibernate4.3.11配置二级缓存了,因为在企业开发中,会大量使用到Hibernate的二级缓存。 由于要在SSH项目中使用到Hibernate4.3.11的二级缓存,所以我们需要向项目中导入Hibernate4.3.11中与二级缓存相关的jar文

李阿昀的博客 5408

Hibernate缓存机制

缓存是位于应用程序与物理数据源之间,用于临时存放复制数据的内存区域,目的是为了减少应用程序对物理数据源访问的次数,从而提高应用程序的运行性能.   Hibernate在查询数据时,首先到缓存中去查找,如果找到就直接使用,找不到的时候就会从物理数据源中检索,所以,把频繁使用的数据加载到缓存区后,就可以大大减少应用程序对物理数据源的访问,使得程序的运行性能明显的提升.   Hibernate缓存分类:...

hty68024352的专栏 171

缓存方案一:EhCache

EhCache EhCache是十分流行的开源缓存框架,解决了关系数据系统数据提取的高花费、高延时问题。 Ehcache 属于轻量级框架,内含持久化机制,保证JVM和服务器重启后数据不会丢失。 Hibernate和Liferay的默认缓存策略就是用Ehcache。 Spring Cache Spring Cache核心就是对某个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的方式存放到缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指定的结果进行返回。 配置方法:

weixin_43166227的博客 486

springboot 2集成hibernate5及ehcache3

1、配置pom文件 <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-jcache</artifactId> <version>${hibernate.version}</version> </dependency> <dependency>

专注成就非凡 730
下一篇: SpringBoot 2.x 使用Redis作为缓存 设置有效时间及自动更新策略
yingziisme
博客等级 码龄15年 105粉丝 60原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值