SpringBoot常用配置介绍

介绍一些springboot的常用配置

一、ehcache 缓存配置

  • 1、添加相关jar包, pom.xml 如下:
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-cacheartifactId>
        dependency>

        
        <dependency>
            <groupId>net.sf.ehcachegroupId>
            <artifactId>ehcacheartifactId>
        dependency>
  • 2、 在resources目录下添加ehcache.xml配置文件,内容如下:
    
    <ehcache 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:noNamespaceSchemaLocation="ehcache.xsd"
        updateCheck="false">

        <diskStore path="java.io.tmpdir"/>

        <defaultCache
                maxElementsInMemory="10000"
                eternal="false"
                timeToIdleSeconds="120"
                timeToLiveSeconds="120"
                overflowToDisk="true"
                maxElementsOnDisk="10000000"
                diskPersistent="false"
                diskExpiryThreadIntervalSeconds="120"
                memoryStoreEvictionPolicy="LRU"
                />

        <cache name="myCache"
               maxElementsInMemory="30"  
               eternal="true"
               timeToIdleSeconds="1800"
               overflowToDisk="true"
               memoryStoreEvictionPolicy="LRU"
               />     
    


    ehcache>
  • 3、 新建一个类: CacheConfiguration, 代码如下:

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

/**
 * 
 * @author ZSX
 */

@Configuration
@EnableCaching // 标注启动缓存
public class CacheConfiguration {


    /**
     * ehcache 主要的管理器
     * @param bean
     * @return
     */
    @Bean
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
        return new EhCacheCacheManager(bean.getObject());
    }


    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
        EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();

        factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factoryBean.setShared(true);

        return factoryBean;
    }
}
  • 4、 调用时也很简单,如下:

在调用类里面注入缓存管理器

@Autowired
    private CacheManager cacheManager;

然后可以根据ehcache.xml配置文件里的缓存名称,指定缓存,并把对象存入缓存

Cache cache = cacheManager.getCache("myCache");
cache.put("code_cache", new Object());

使用缓存时,只需要get,并强转一下即可

ValueWrapper valueWrapper = cache.get("code_cache");
Map<String, Object> map = (Map<String, Object>) valueWrapper.get();

你可能感兴趣的:(SpringBoot)