学习springboot小笔记(七) ----启动类不能放在java目录下、缓存的使用步骤介绍

一、springboot的启动类不能放在java目录下!!!必须要个包将它包进去

否则会报错误:

Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.

这个原因值得注意就是因为有时候很难在IDEA中的项目目录认出来这个错误。

             

                         

                          正常的                                                      错误的

如果不是细心去看,真的会被坑一下哈。

不过,如果自己正常操作也不会造成这种情况的,我是无意中弄到了这个,没看出来。

如果是在移动不了,就到文件目录移动,不过之后就的手动改一下package的名字了。

二、缓存的使用

(一)共同操作:

首先引入依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

其次,在Spring Boot主类中增加@EnableCaching注解开启缓存功能
Spring Boot根据下面的顺序去侦测缓存提供者:默认的缓存实现是:ConcurrentMapCacheManager

  • JCache (JSR-107)
  • EhCache 2.x
  • Hazelcast
  • Infinispan
  • Redis
  • Guava
  • Simple

然后,在数据访问接口(repository层或者说Dao层)中配置 缓存配置注解 @CacheConfig(cacheNames=“users”),这个表示 该数据访问对象中返回的内容将存储于名为users的缓存对象中

再者、对应的操作函数也要加上@Cacheable。Eg:

//将下面函数的返回值加入缓存,同时,在查询时候,会先从缓存中获取,若不在才会发起对数据库的访问
//condition表示条件,只有当第一个参数的长度小于10的时候才会被缓存,
//也就是name的长度超过10的话,就不会被缓存了的。
@Cacheable(key="#p0",condition="#p0.length() < 10")
User findByName(String name);

最后,通过重复访问一个数据,查看是否 有重复的sql语句(在配置文件应该加上:

#开启hibernate对sql的打印
spring.jpa.properties.hibernate.show_sql=true

)对数据库访问。

若无重复,则是缓存起作用了。

若是重复了,则缓存不起作用。

在这里只是采用了默认的缓存实现方法ConcurrentMapCacheManager。

 

(二)选择操作--选择不同的缓存实现

    (1) 使用ehcache实现缓存的步骤:  

    1.添加依赖

<dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache</artifactId>
</dependency>

   2.新建ehcache的xml配置文件

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">

    <cache name="Users"
           maxEntriesLocalHeap="200"
           timeToLiveSeconds="600">
    </cache>

</ehcache>

<这样子就好了,运行程序,debug状态下面可以看见,CacheManager的对象是EhCacheManager

 (2)使用redis实现缓存的步骤

      首先、本地的redis环境先搭建好。

       其次,引入依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

在application.properties中配置redis

#redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1

再者,缓存成员类需要继承接口Serialiazable。

然后就可以用test测试了。

 

猜你喜欢

转载自blog.csdn.net/zhang_li_ke/article/details/81225586