Spring使用Ehcache

spring集成ehcache 问题背景:一些业务场景中,一些数据往往是长期不变更,但数据使用较多。为了满足系统性能需要,可以借助本地缓存去使用,保证同一个JVM实例只保存一份内存,提高系统可用性。基于这个背景,这里将介绍ehcache缓存。在springboot集成ehcache这篇文章中已经介绍过,这里介绍下springmvc去集成使用。 阅读详情

之前对于Ehcache的了解仅限于它可以作为Hibernate的二级缓存,偶然间程序中用到了它来做简单的缓存,发现还挺好的,比如用来缓存一下系统配置什么的,或者一些小的项目,犯不着用redis之类的,可以考虑一下用这个玩意儿。

转载来一篇文章,介绍如何跟Spring整合的:

从3.1开始,Spring引入了对Cache的支持。其使用方法和原理都类似于Spring对事务管理的支持。Spring Cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存放在缓存中,等到下次利用同样的参数来调用该方法时将不再执行该方法,而是直接从缓存中获取结果进行返回。所以在使用Spring Cache的时候我们要保证我们缓存的方法对于相同的方法参数要有相同的返回结果。

使用Spring Cache需要我们做两方面的事:

  • 声明某些方法使用缓存
  • 配置Spring对Cache的支持

和Spring对事务管理的支持一样,Spring对Cache的支持也有基于注解和基于XML配置两种方式。下面我们先来看看基于注解的方式。

1 基于注解的支持

   Spring为我们提供了几个注解来支持Spring Cache。其核心主要是@Cacheable和@CacheEvict。使用@Cacheable标记的方法在执行后Spring Cache将缓存其返回结果,而使用@CacheEvict标记的方法会在方法执行前或者执行后移除Spring Cache中的某些元素。下面我们将来详细介绍一下Spring基于注解对Cache的支持所提供的几个注解。

1.1 @Cacheable

@Cacheable可以标记在一个方法上,也可以标记在一个类上。当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的。对于一个支持缓存的方法,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。Spring在缓存方法的返回值时是以键值对进行缓存的,值就是方法的返回结果,至于键的话,Spring又支持两种策略,默认策略和自定义策略,这个稍后会进行说明。需要注意的是当一个支持缓存的方法在对象内部被调用时是不会触发缓存功能的。@Cacheable可以指定三个属性,value、key和condition。

1.1.1 value属性指定Cache名称

value属性是必须指定的,其表示当前方法的返回值是会被缓存在哪个Cache上的,对应Cache的名称。其可以是一个Cache也可以是多个Cache,当需要指定多个Cache时其是一个数组。

   @Cacheable("cache1")//Cache是发生在cache1上的
   public User find(Integer id) {
      returnnull;
   }

   @Cacheable({"cache1", "cache2"})//Cache是发生在cache1和cache2上的
   public User find(Integer id) {
      returnnull;
   }
1.1.2 使用key属性自定义key

key属性是用来指定Spring缓存方法的返回结果时对应的key的。该属性支持SpringEL表达式。当我们没有指定该属性时,Spring将使用默认策略生成key。我们这里先来看看自定义策略,至于默认策略会在后文单独介绍。

自定义策略是指我们可以通过Spring的EL表达式来指定我们的key。这里的EL表达式可以使用方法参数及它们对应的属性。使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。下面是几个使用参数作为key的示例。


   @Cacheable(value="users", key="#id")
   public User find(Integer id) {
      returnnull;
   }

   @Cacheable(value="users", key="#p0")
   public User find(Integer id) {
      returnnull;
   }

   @Cacheable(value="users", key="#user.id")
   public User find(User user) {
      returnnull;
   }

   @Cacheable(value="users", key="#p0.id")
   public User find(User user) {
      returnnull;
   }

除了上述使用方法参数作为key之外,Spring还为我们提供了一个root对象可以用来生成key。通过该root对象我们可以获取到以下信息:

属性名称描述示例
methodName当前方法名root.methodName
method当前方法root.method.name
target当前被调用的对象root.target
targetClass当前被调用的对象的classroot.targetClass
args当前方法参数组成的数组root.args[0]
caches当前被调用的方法使用的Cacheroot.caches[0].name
   当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。如:

@Cacheable(value={“users”, “xxx”}, key=”caches[1].name”)
public User find(User user) {
returnnull;
}

1.1.3 condition属性指定发生的条件

有的时候我们可能并不希望缓存一个方法所有的返回结果。通过condition属性可以实现这一功能。condition属性默认为空,表示将缓存所有的调用情形。其值是通过SpringEL表达式来指定的,当为true时表示进行缓存处理;当为false时表示不进行缓存处理,即每次调用该方法时该方法都会执行一次。如下示例表示只有当user的id为偶数时才会进行缓存。

   @Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")
   public User find(User user) {
      System.out.println("find user by user " + user);
      return user;
   }

1.2 @CachePut

在支持Spring Cache的环境下,对于使用@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。@CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
@CachePut也可以标注在类上和方法上。使用@CachePut时我们可以指定的属性跟@Cacheable是一样的。

   @CachePut("users")//每次都会执行方法,并将结果存入指定的缓存中
   public User find(Integer id) {
      returnnull;
   }

1.3 @CacheEvict

@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。其中value、key和condition的语义与@Cacheable对应的属性类似。即value表示清除操作是发生在哪些Cache上的(对应Cache的名称);key表示需要清除的是哪个key,如未指定则会使用默认策略生成的key;condition表示清除操作发生的条件。下面我们来介绍一下新出现的两个属性allEntries和beforeInvocation。

1.3.1 allEntries属性

allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。

   @CacheEvict(value="users", allEntries=true)
   public void delete(Integer id) {
      System.out.println("delete user by id: " + id);
   }
1.3.2 beforeInvocation属性

清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。

   @CacheEvict(value="users", beforeInvocation=true)
   public void delete(Integer id) {
      System.out.println("delete user by id: " + id);
   }

其实除了使用@CacheEvict清除缓存元素外,当我们使用Ehcache作为实现时,我们也可以配置Ehcache自身的驱除策略,其是通过Ehcache的配置文件来指定的。由于Ehcache不是本文描述的重点,这里就不多赘述了,想了解更多关于Ehcache的信息,请查看我关于Ehcache的专栏。

1.4 @Caching

@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。

   @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
         @CacheEvict(value = "cache3", allEntries = true) })
   public User find(Integer id) {
      returnnull;
   }

1.5 使用自定义注解

Spring允许我们在配置可缓存的方法时使用自定义的注解,前提是自定义的注解上必须使用对应的注解进行标注。如我们有如下这么一个使用@Cacheable进行标注的自定义注解。

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Cacheable(value="users")
public @interface MyCacheable {

}

那么在我们需要缓存的方法上使用@MyCacheable进行标注也可以达到同样的效果。

   @MyCacheable
   public User findById(Integer id) {
      System.out.println("find user by id: " + id);
      User user = new User();
      user.setId(id);
      user.setName("Name" + id);
      return user;
   }

2 配置Spring对Cache的支持

2.1 声明对Cache的支持

2.1.1 基于注解

配置Spring对基于注解的Cache的支持,首先我们需要在Spring的配置文件中引入cache命名空间,其次通过就可以启用Spring对基于注解的Cache的支持。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:cache="http://www.springframework.org/schema/cache"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/cache
     http://www.springframework.org/schema/cache/spring-cache.xsd">

   <cache:annotation-driven/>

</beans>

有一个cache-manager属性用来指定当前所使用的CacheManager对应的bean的名称,默认是cacheManager,所以当我们的CacheManager的id为cacheManager时我们可以不指定该参数,否则就需要我们指定了。

还可以指定一个mode属性,可选值有proxy和aspectj。默认是使用proxy。当mode为proxy时,只有缓存方法在外部被调用的时候Spring Cache才会发生作用,这也就意味着如果一个缓存方法在其声明对象内部被调用时Spring Cache是不会发生作用的。而mode为aspectj时就不会有这种问题。另外使用proxy时,只有public方法上的@Cacheable等标注才会起作用,如果需要非public方法上的方法也可以使用Spring Cache时把mode设置为aspectj。

此外,还可以指定一个proxy-target-class属性,表示是否要代理class,默认为false。我们前面提到的@Cacheable、@cacheEvict等也可以标注在接口上,这对于基于接口的代理来说是没有什么问题的,但是需要注意的是当我们设置proxy-target-class为true或者mode为aspectj时,是直接基于class进行操作的,定义在接口上的@Cacheable等Cache注解不会被识别到,那对应的Spring Cache也不会起作用了。

需要注意的是只会去寻找定义在同一个ApplicationContext下的@Cacheable等缓存注解。

2.1.2 基于XML配置

除了使用注解来声明对Cache的支持外,Spring还支持使用XML来声明对Cache的支持。这主要是通过类似于aop:advice的cache:advice来进行的。在cache命名空间下定义了一个cache:advice元素用来定义一个对于Cache的advice。其需要指定一个cache-manager属性,默认为cacheManager。cache:advice下面可以指定多个cache:caching元素,其有点类似于使用注解时的@Caching注解。cache:caching元素下又可以指定cache:cacheable、cache:cache-put和cache:cache-evict元素,它们类似于使用注解时的@Cacheable、@CachePut和@CacheEvict。下面来看一个示例:

   <cache:advice id="cacheAdvice" cache-manager="cacheManager">
      <cache:caching cache="users">
         <cache:cacheable method="findById" key="#p0"/>
         <cache:cacheable method="find" key="#user.id"/>
         <cache:cache-evict method="deleteAll" all-entries="true"/>
      </cache:caching>
   </cache:advice>

上面配置定义了一个名为cacheAdvice的cache:advice,其中指定了将缓存findById方法和find方法到名为users的缓存中。这里的方法还可以使用通配符“”,比如“find”表示任何以“find”开始的方法。

有了cache:advice之后,我们还需要引入aop命名空间,然后通过aop:config指定定义好的cacheAdvice要应用在哪些pointcut上。如:

   <aop:config proxy-target-class="false">
      <aop:advisor advice-ref="cacheAdvice" pointcut="execution(* com.xxx.UserService.*(..))"/>
   </aop:config>

上面的配置表示在调用com.xxx.UserService中任意公共方法时将使用cacheAdvice对应的cache:advice来进行Spring Cache处理。更多关于Spring Aop的内容不在本文讨论范畴内。

2.2 配置CacheManager

CacheManager是Spring定义的一个用来管理Cache的接口。Spring自身已经为我们提供了两种CacheManager的实现,一种是基于Java API的ConcurrentMap,另一种是基于第三方Cache实现——Ehcache,如果我们需要使用其它类型的缓存时,我们可以自己来实现Spring的CacheManager接口或AbstractCacheManager抽象类。下面分别来看看Spring已经为我们实现好了的两种CacheManager的配置示例。
2.2.1 基于ConcurrentMap的配置

   <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
      <property name="caches">
         <set>
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="xxx"/>
         </set>
      </property>
   </bean>

上面的配置使用的是一个SimpleCacheManager,其中包含一个名为“xxx”的ConcurrentMapCache。

2.2.2 基于Ehcache的配置
   <!-- Ehcache实现 -->
   <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcacheManager"/>
   <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache-spring.xml"/>

上面的配置使用了一个Spring提供的EhCacheCacheManager来生成一个Spring的CacheManager,其接收一个Ehcache的CacheManager,因为真正用来存入缓存数据的还是Ehcache。Ehcache的CacheManager是通过Spring提供的EhCacheManagerFactoryBean来生成的,其可以通过指定ehcache的配置文件位置来生成一个Ehcache的CacheManager。若未指定则将按照Ehcache的默认规则取classpath根路径下的ehcache.xml文件,若该文件也不存在,则获取Ehcache对应jar包中的ehcache-failsafe.xml文件作为配置文件。更多关于Ehcache的内容这里就不多说了,它不属于本文讨论的内容,欲了解更多关于Ehcache的内容可以参考我之前发布的Ehcache系列文章,也可以参考官方文档等。

3 键的生成策略

   键的生成策略有两种,一种是默认策略,一种是自定义策略。

3.1 默认策略

默认的key生成策略是通过KeyGenerator生成的,其默认策略如下:
- 如果方法没有参数,则使用0作为key。
- 如果只有一个参数的话则使用该参数作为key。
- 如果参数多余一个的话则使用所有参数的hashCode作为key。

如果我们需要指定自己的默认策略的话,那么我们可以实现自己的KeyGenerator,然后指定我们的Spring Cache使用的KeyGenerator为我们自己定义的KeyGenerator。

使用基于注解的配置时是通过cache:annotation-driven指定的.

   <cache:annotation-driven key-generator="userKeyGenerator"/>

   <bean id="userKeyGenerator" class="com.xxx.cache.UserKeyGenerator"/>

而使用基于XML配置时是通过cache:advice来指定的。

   <cache:advice id="cacheAdvice" cache-manager="cacheManager" key-generator="userKeyGenerator">
   </cache:advice>

需要注意的是此时我们所有的Cache使用的Key的默认生成策略都是同一个KeyGenerator。

3.2 自定义策略

自定义策略是指我们可以通过Spring的EL表达式来指定我们的key。这里的EL表达式可以使用方法参数及它们对应的属性。使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。下面是几个使用参数作为key的示例。

   @Cacheable(value="users", key="#id")
   public User find(Integer id) {
      returnnull;
   }

   @Cacheable(value="users", key="#p0")
   public User find(Integer id) {
      returnnull;
   }

   @Cacheable(value="users", key="#user.id")
   public User find(User user) {
      returnnull;
   }

   @Cacheable(value="users", key="#p0.id")
   public User find(User user) {
      returnnull;
   }

除了上述使用方法参数作为key之外,Spring还为我们提供了一个root对象可以用来生成key。通过该root对象我们可以获取到以下信息:

属性名称描述示例
methodName当前方法名
method当前方法
target当前被调用的对象
targetClass当前被调用的对象的class
args当前方法参数组成的数组
caches当前被调用的方法使用的Cache

当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。如:

   @Cacheable(value={"users", "xxx"}, key="caches[1].name")
   public User find(User user) {
      returnnull;
   }

4 Spring单独使用Ehcache

前面介绍的内容是Spring内置的对Cache的支持,其实我们也可以通过Spring自己单独的使用Ehcache的CacheManager或Ehcache对象。通过在Application Context中配置EhCacheManagerFactoryBean和EhCacheFactoryBean,我们就可以把对应的EhCache的CacheManager和Ehcache对象注入到其它的Spring bean对象中进行使用。

4.1 EhCacheManagerFactoryBean

EhCacheManagerFactoryBean是Spring内置的一个可以产生Ehcache的CacheManager对象的FactoryBean。其可以通过属性configLocation指定用于创建CacheManager的Ehcache配置文件的路径,通常是ehcache.xml文件的路径。如果没有指定configLocation,则将使用默认位置的配置文件创建CacheManager,这是属于Ehcache自身的逻辑,即如果在classpath根路径下存在ehcache.xml文件,则直接使用该文件作为Ehcache的配置文件,否则将使用ehcache-xxx.jar中的ehcache-failsafe.xml文件作为配置文件来创建Ehcache的CacheManager。此外,如果不希望创建的CacheManager使用默认的名称(在ehcache.xml文件中定义的,或者是由CacheManager内部定义的),则可以通过cacheManagerName属性进行指定。下面是一个配置EhCacheManagerFactoryBean的示例。

   <!-- 定义CacheManager -->
   <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
      <!-- 指定配置文件的位置 -->
      <property name="configLocation" value="/WEB-INF/config/ehcache.xml"/>
      <!-- 指定新建的CacheManager的名称 -->
      <property name="cacheManagerName" value="cacheManagerName"/>
   </bean>

4.2 EhCacheFactoryBean

   EhCacheFactoryBean是用来产生Ehcache的Ehcache对象的FactoryBean。定义EhcacheFactoryBean时有两个很重要的属性我们可以来指定。一个是cacheManager属性,其可以指定将用来获取或创建Ehcache的CacheManager对象,若未指定则将通过CacheManager.create()获取或创建默认的CacheManager。另一个重要属性是cacheName,其表示当前EhCacheFactoryBean对应的是CacheManager中的哪一个Ehcache对象,若未指定默认使用beanName作为cacheName。若CacheManager中不存在对应cacheName的Ehcache对象,则将使用CacheManager创建一个名为cacheName的Cache对象。此外我们还可以通过EhCacheFactoryBean的timeToIdle、timeToLive等属性指定要创建的Cache的对应属性,注意这些属性只对CacheManager中不存在对应Cache时新建的Cache才起作用,对已经存在的Cache将不起作用,更多属性设置请参考Spring的API文档。此外还有几个属性是对不管是已经存在还是新创建的Cache都起作用的属性:statisticsEnabled、sampledStatisticsEnabled、disabled、blocking和cacheEventListeners,其中前四个默认都是false,最后一个表示为当前Cache指定CacheEventListener。下面是一个定义EhCacheFactoryBean的示例。
   <!-- 定义CacheManager -->
   <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
      <!-- 指定配置文件的位置 -->
      <property name="configLocation" value="/WEB-INF/config/ehcache.xml"/>
      <!-- 指定新建的CacheManager的名称 -->
      <property name="cacheManagerName" value="cacheManagerName"/>
   </bean>

   <!-- 定义一个Ehcache -->
   <bean id="userCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
      <property name="cacheName" value="user"/>
      <property name="cacheManager" ref="cacheManager"/>
   </bean>

(注:本文是基于Spring3.1.0所写)

系列文章

Spring整合EhCache详细教程(史上最全) sping整合ehcache实现二级缓存,从根本上了解spring缓存机制,自己实现不用愁 立即下载

相关推荐

如何制作微信小程序的在线购物商城应用

首先,你需要规划好商城的整体框架,确定好你的目标用户群体,思考他们的需求是什么。接下来,使用微信开发者工具创建一个新的小程序项目,输入你的AppID,选择好保存路径,点击“创建”,一个新的商城雏形就诞生了。你可以把这里当作自己的家,无论是工作之余的小憩,还是寻找灵感的驿站,我都希望你能在这里找到属于你的那份快乐和满足。数据是现代商业的灵魂,通过数据分析,你可以更准确地把握用户的行为模式,从而做出更明智的决策。

master_chenchen的博客 2427

Spring使用EhCache

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33694620的博客 208

STM32驱动HC-SR04超声波模块:两种精准测距方案详解

本文详解STM32驱动HC-SR04超声波模块的两种精准测距方案:定时器中断计数法和外部中断边沿检测法。涵盖硬件连接、代码实现与优化技巧,帮助开发者根据精度和复杂度需求选择合适方案,提升超声波测距在嵌入式项目中的稳定性和准确性。

g5h6i的博客 682

Spring 使用 Ehcache 技术指南

在 Java 企业应用开发中,缓存是一种非常重要的技术,可以有效提高应用的性能和响应速度。Ehcache 是一个非常流行的开源缓存解决方案,广泛应用于各种 Java 应用中。本文将介绍如何在 Spring 框架中集成和使用 Ehcache。

FireFox1997 1037

CMake、Make、MinGw、Clang、Llvm、GCC、MSVC的区别

除开 GCC (GNU 编译器集合) 以外,MinGW 还包含有一些其他的 GNU 程序开发工具;的缩写,MinGw是windows版本的gcc集合。并不仅是一个 C/C++ 编译器,而是一套。是微软开发的VC运行时库,3、Make和CMake是。

m0_37698164的博客 1万+

跨平台烧录实战:RKDevTool在Windows/Linux/MacOS下的统一与差异

本文详细解析了RKDevTool在Windows、Linux和macOS三大操作系统下的固件烧录实践,重点介绍了RK3576开发板的环境配置、工具链选择、烧录模式切换及常见问题解决方案,帮助开发者构建稳定可靠的跨平台烧录工作流。

cnn8visionary的博客 202

SpringBoot中使用Ehcache的详细教程

SpringBoot中使用Ehcache的详细教程

佳佳乐的博客 5162

【一张图系列】别再混淆了!5分钟搞懂ERP、MES、PLC的职责边界与数据流》

《ERP、MES、PLC系统边界与协作解析》一文清晰阐述了制造业三大核心系统的角色分工与数据流转。文章将ERP比作企业"大脑"负责战略规划,MES作为车间"指挥官"负责执行调度,PLC则是设备"士兵"执行具体操作。通过一张架构图展示了从计划层到控制层的完整信息流:蓝色箭头表示指令下行(ERP→MES→PLC),橙色箭头代表数据上行反馈(PLC→MES→ERP)。文章强调理清系统边界对数字化转型、部门协作和项目实施的关键作用,并预告下期将深入解析ME

「东哥说MES」 专注于MES制造执行系统,为你拆解核心架构、功能模块及与ERP/PLC的集成逻辑。提供从入门到精通的系列干货、精选行业报告与实用工具,构建你的数字化知识体系,关注我,用实战经验照亮你的数字化之路。 970

在 Spring 中使用 @EhCache 注解作为缓存

Spring 有一个内置的 EhCache 缓存管理器。这适用于大多数缓存情况,但我发现定义自定义缓存管理器非常有用,因为它允许我使用相同的缓存管理器以编程方式或通过注释控制缓存。本文重点介绍 annotations,但让我们继续定义一个自定义缓存管理器,以便在需要时做好准备。如果您更喜欢坚持使用 默认缓存管理器 ,您可以跳过此步骤。我们将在 :super();

龚小帅的博客 2051

ContextCapture系列教程(三):大疆精灵4RTK版无人机POS数据提取、处理(处理后勉强达到免相控要求)

大疆精灵 Phantom 4 RTK于2018年发布,是大疆为高精度建图与精准飞行设计的行业级无人机,在精灵4无人机外形的基础上,机身增加了RTK模块,可以实现高精度 RTK 定位导航,相机与 RTK 系统采用微秒级时间同步,可以通过app 进行航线规划飞行

pausau的博客 1万+

基于 Qt C++ 的 船舶导航系统 UI

你想实现一个基于 **Qt C++** 的 **船舶导航系统 UI**,核心功能包括 **Qt Quick** 电子海图显示和 **NMEA 0183** 协议解析。"断开" : "连接"创建一个 Qt Quick 项目,选择 **Qt 6** 版本,确保勾选 **Qt Quick**、**Qt Network** 和 **Qt SQL** 模块。Label { text: "纬度:" }3. **连接设备**:点击 "连接" 按钮连接到 GPS 设备或模拟数据源。title: "连接设置"

寒寒豆豆软件公司的博客 127

Spring Boot文档阅读笔记-EhCache的使用

这里要先注意2个概念: buffer和cache,很多人会讲这两个概念混用。但其实这是两个概念! buffer:一般是指存储临时数据的实体。只能读写一次,对于程序员来说buffer是可见的,比如TCB中,接收tcp数据的buffer。 cache:对于程序员来说是不可见的。允许多次获取相同的数据。这也就是EhCache不叫EhBuffer的原因。 程序结构如下: 首先来看下pom.xml <?xml version="1.0" encoding="UTF-8"?&g...

IT1995的博客 1183

基于STM32L4XX、HAL库的MMA8452QR1姿态传感器驱动程序设计

/ HAL库需要左移1位。#define MMA8452Q_I2C_ADDRESS 0x1D // SA0=1时的地址。* @param range: 量程(MMA8452Q_RANGE_2G/4G/8G)* @param haccel: MMA8452Q句柄。* @param haccel: MMA8452Q句柄。* @param haccel: MMA8452Q句柄。* @param haccel: MMA8452Q句柄。* @param haccel: MMA8452Q句柄。

zhusl6688的博客 770

Spring使用Cache、整合Ehcache

Spring使用Cache、整合Ehcache         从3.1开始,Spring引入了对Cache的支持。其使用方法和原理都类似于Spring对事务管理的支持。Spring Cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存放在缓存中,等到下次利用同样的参数来调用该方法时将不再执行该方法,而是直接从缓存中获取结果进行返回。所

Elim的博客 1万+

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

深度学习工具包 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")

spring + ehcache 使用实例

1 spring与ehcache结合使用,需要导入如下的包:ehcache , commons-logging , cglib , asm , spring的jar包具体版本可以选择最新。2 spring配置文件applicationContext.xml如下:

先相信你自己,然后别人才会相信你。 3万+

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

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

spring 集成 ehcache

一、准备工作 需要依赖 jar 包: 1.ehcache核心包                net.sf.ehcache        ehcache-core     2.spring 扩展包        org.springframework        spring-context-support     二、编程开发 1.ehcache.

wyc2410的专栏 880

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

EHCache Spring

从 Spring 1.1.1 开始,EHCache 就作为一种通用缓存解决方案集成进 Spring。我将示范拦截器的例子,它能把方法返回的结果缓存起来。 利用 Spring IoC 配置 EHCache在 Spring 里配置 EHCache 很简单。你只需一个 ehcache.xml 文件,该文件用于配置 EHCache:&lt;ehcache&gt;     &lt;!—设置缓存文件 ....

qiuyabing的专栏 156

spring EhCache缓存之annotation注解

spring + ehcache 注解使用实例 EhCache缓存之annotation注解

lemonzone2010的专栏 1万+

如何在Spring Boot中使用EhCache缓存

在查询数据的时候,数据大多来自于数据库,我们会基于SQL语句与数据库交互,数据库一般会基于本地磁盘IO将数据读取到内存,返回给Java服务端,我们再将数据响应给前端,做数据展示。但是MySQL这种关系型数据库查询数据相对比较慢,因为有磁盘IO,或者是全盘扫描的风险,在针对一些热点数据时,会对MySQL造成比较大的压力,此时我们可以采用缓存的方式来解决。而缓存又分为很多种,相对服务端角度来说,可以采用Redis和JVM这两种方式。

weixin_73412838的博客 3750

Spring和Ehcache整合详解

Spring和Ehcache整合详解 一、官方主页 Spring Cache 二、概述 EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点. Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现。它支持注解方式使用缓存,非常方便。 Ehcache是使用的是本地的内存做缓存,而redis则是部署在另一个server...

feiyangtianyao的专栏 1万+

Spring集成ehcache

1.导入jar包 ehcache-core-2.4.5.jar ehcache-spring-annotations-1.2.0.jar(使用spring注解的形式配置时需要引入的jar包,依赖于guava) ehcache-web-2.0.4.jar(做页面缓存需要用到) guava-r09.jar(google推出可以帮助你写出更优雅代码的工具,和apache-commons差不多)

太匆匆 1142

spring4配置基于注解的ehcache缓存

一、 ehcache配置文件ehcache.xml xml version="1.0" encoding="UTF-8"?> ehcache name="es">       diskStore path="java.io.tmpdir"/>       defaultCache         maxElementsInMemory="10000"  eterna

愿夜幕永不开启 5871

Spring整合ehcache

配置文件导入maven坐标<!-- ehcache缓存 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.11</version> </dependency> Spring整合ehcache包 spring-context-

AsakuraNatsuhi的博客 1181

ehcache 整合 spring

applicationContext-ehcache.xml  &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan...

The Secret 308

EhCache的使用及与Spring的整合

本文主要介绍EhCache的使用,以及EhCache与Spring的整合的实践经验。 EHCache API的基本用法 首先介绍CacheManager类。它主要负责读取配置文件,默认读取CLASSPATH下的ehcache.xml,根据配置文件创建并管理Cache对象。 // 使用默认配置文件创建CacheManager CacheManag

special dream的博客 2512
上一篇: 一些shell代码片段
下一篇: Spring Boot入门(连接MySQL, Redis 输出JSP)
java_4_ever
博客等级 码龄16年 8粉丝 29原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值