SpringBoot整合ehcache实现业务缓存

1、ehcache的依赖pom.xml

        <!-- caching -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
		</dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.2</version>
        </dependency>

2、ehcache.xml配置

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

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <defaultCache
            eternal="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="600"
            memoryStoreEvictionPolicy="LRU" />

    <!-- 这里的 users 缓存空间是为了下面的 demo 做准备 -->
    <cache
            name="users"
            eternal="false"
            maxElementsInMemory="100"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="300"
            memoryStoreEvictionPolicy="LRU" />
            
</ehcache>

3、yml文件配置

spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        platform: mysql
        #url: jdbc:mysql://192.168.1.183:20001/dna?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSl=false
        url: jdbc:mysql://127.0.0.1:3306/ly?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSl=false
        username: root
        password: 123456
        initialSize: 10
        minIdle: 10
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        filters: stat,wall,log4j2
        logSlowSql: true
    http:
        encoding:
                charset: utf-8
                enabled: true
                force: true
    cache:
      type: ehcache
      ehcache:
        config: classpath:ehcache.xml

4、工具类

package com.example.demo.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.util.List;

/**
 * 
 *  @desc工具类
 *	@author luobw
 * 
 *  2019年4月28日
 */
public class EhcacheUtil {

    private static CacheManager cacheManager = CacheManager.create();

    /**
     * 根据key值从缓存得到value
     * @param cacheName
     * @param key
     * @return
     */
    public static Object get(String cacheName, Object key) {
        Cache cache = cacheManager.getCache(cacheName);
        if(cache!= null) {
            Element element = cache.get(key);
            if(element != null) {
                return element.getObjectValue();
            }
        }
        return null;
    }

    /**
     * 把对应key和vlaue数据存储到缓存
     * @param cacheName
     * @param key
     * @param value
     */
    public static void put(String cacheName, Object key, Object value) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            cache.put(new Element(key, value));
        }
    }

    /**
     * 根据k移除涉及权限的value
     * @param key
     * @return
     */
    public static boolean remove(String cacheName, Object key) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            return cache.remove(key);
        }
        return false;
    }

    public static void removeAll(String cacheName, List<String> keys) {
        Cache cache = cacheManager.getCache(cacheName);
        cache.removeAll(keys);
    }

}

5、自动适配,启动方式上注入缓存

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;

import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@SpringBootApplication
@MapperScan("com.example.demo.ehcache")
@EnableCaching
public class Demo1Application {

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

}

6、业务层处理缓存

package com.example.demo.ehcache;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import net.sf.ehcache.CacheException;

@Service
public class UserService {

    //这里的单引号不能少,否则会报错,被识别是一个对象
    private static final String CACHE_KEY = "'user'";
    private static final String DEMO_CACHE_NAME = "users";
    //private static final String list_CACHE_NAME = "list";
    

    @Autowired
    private UserDao userDao;

	//删除用户数据
	@CacheEvict(value = DEMO_CACHE_NAME,key = "'user_'+#uuid")//这是清除缓存
	public void delete1(String uuid){
	    userDao.delete(uuid);
	}
	
	//更新用户数据
	@CachePut(value = DEMO_CACHE_NAME,key = "'user_'+#user.getUuid()")
	public User update(User user) throws CacheException{
	    User user1 = userDao.findByUuid(user.getUuid());
	    if (null == user1){
	        throw new  CacheException("Not Find");
	    }
	    user1.setAge(user.getAge());
	    user1.setName(user.getName());
	    return user1;
	}
	
	//查找用户数据
	@Cacheable(value=DEMO_CACHE_NAME,key="'user_'+#uuid")
	public User findByUuid(String uuid){
	    //若找不到缓存将打印出提示语句
	    System.err.println("没有走缓存!"+uuid);
	    return userDao.findByUuid(uuid);
	}
	
	//保存用户数据
	@CacheEvict(value=DEMO_CACHE_NAME,key=CACHE_KEY)
	public int save(User user){
	    return userDao.save(user);
	}
    public static final String THING_ALL_KEY  = "\"thing_all\"";
    @Cacheable(value=DEMO_CACHE_NAME,key=CACHE_KEY)
	public List<User> list(User user) {
    	System.out.println("--首次查询数据库-");
		// TODO Auto-generated method stub
		return userDao.list();
	}
    @CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY)//这是清除缓存
	public void delete(String uuid){
	    userDao.delete(uuid);
	}
}

7、简单的controller层接受请求

package com.example.demo.ehcache;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.log4j.Log4j2;
import net.sf.ehcache.CacheException;

@RestController
@Log4j2
public class EhcacheController {


    @Autowired
    private UserService userService;

    @RequestMapping("/encache")
    public String EhcacheTest() throws Exception{
        log.debug("进行Encache缓存测试");
        User users = new User();
        List<User> list =	userService.list( users);
        return JSONObject.toJSONString(list);
    }
    @RequestMapping("/delete")
    public String delete() {
    	String id = "";
		 userService.delete(id);
		return "success";
    	
    }
}

8、运行效果

第一次请求:

第二次请求

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值