1. 程式人生 > 實用技巧 >快取類似於redis

快取類似於redis

第一

package com.sxt.sys.cache;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sxt.bus.domain.Customer;
import com.sxt.bus.domain.Goods;
import com.sxt.bus.domain.Provider;
import com.sxt.bus.mapper.CustomerMapper;
import com.sxt.bus.mapper.GoodsMapper;
import com.sxt.bus.mapper.ProviderMapper;
import com.sxt.sys.common.SpringUtil;
import com.sxt.sys.domain.Dept;
import com.sxt.sys.domain.User;
import com.sxt.sys.mapper.DeptMapper;
import com.sxt.sys.mapper.UserMapper;

/**
 * 快取
 * @author LJH
 *
 */
public class CachePool {
    
    /**
     * 所有的快取資料放到這個CACHE_CONTAINER類似於redis
     */
    public static volatile Map
<String, Object> CACHE_CONTAINER = new HashMap<>(); /** * 根據KEY刪除快取 * @param key */ public static void removeCacheByKey(String key) { if(CACHE_CONTAINER.containsKey(key)) { CACHE_CONTAINER.remove(key); } } /** * 清空所有快取 * @param key */ public static void removeAll() { CACHE_CONTAINER.clear(); } /** * 同步快取 */ public static void syncData() { //同步部門資料 DeptMapper deptMapper = SpringUtil.getBean(DeptMapper.class); List
<Dept> deptList = deptMapper.selectList(null); for (Dept dept : deptList) { CACHE_CONTAINER.put("dept:"+dept.getId(), dept); } //同步使用者資料 UserMapper userMapper = SpringUtil.getBean(UserMapper.class); List<User> userList = userMapper.selectList(null); for (User user : userList) { CACHE_CONTAINER.put("user:"+user.getId(), user); } //同步客戶資料 CustomerMapper customerMapper = SpringUtil.getBean(CustomerMapper.class); List
<Customer> customerList = customerMapper.selectList(null); for (Customer customer : customerList) { CACHE_CONTAINER.put("customer:"+customer.getId(), customer); } //同步供應商資料 ProviderMapper providerMapper = SpringUtil.getBean(ProviderMapper.class); List<Provider> providerList = providerMapper.selectList(null); for (Provider provider : providerList) { CACHE_CONTAINER.put("customer:"+provider.getId(), provider); } //同步商品資料 GoodsMapper goodsMapper=SpringUtil.getBean(GoodsMapper.class); List<Goods> goodsList = goodsMapper.selectList(null); for (Goods goods : goodsList) { CACHE_CONTAINER.put("goods:"+goods.getId(), goods); } } }

第二,切面

package com.sxt.sys.cache;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import com.sxt.sys.domain.Dept;
import com.sxt.sys.domain.User;

@Aspect
@Component
@EnableAspectJAutoProxy
public class CacheAspect {

    /**
     * 日誌出處
     */
    private Log log = LogFactory.getLog(CacheAspect.class);

    // 宣告一個快取容器
    private static Map<String, Object> CACHE_CONTAINER = CachePool.CACHE_CONTAINER;

    public static Map<String, Object> getCACHE_CONTAINER() {
        return CACHE_CONTAINER;
    }
    
    // 宣告切面表示式
    private static final String POINTCUT_DEPT_ADD = "execution(* com.sxt.sys.service.impl.DeptServiceImpl.save(..))";
    private static final String POINTCUT_DEPT_UPDATE = "execution(* com.sxt.sys.service.impl.DeptServiceImpl.updateById(..))";
    private static final String POINTCUT_DEPT_GET = "execution(* com.sxt.sys.service.impl.DeptServiceImpl.getById(..))";
    private static final String POINTCUT_DEPT_DELETE = "execution(* com.sxt.sys.service.impl.DeptServiceImpl.removeById(..))";

    private static final String CACHE_DEPT_PROFIX = "dept:";

    /**
     * 部門新增切入
     * 
     * @throws Throwable
     */
    @Around(value = POINTCUT_DEPT_ADD)
    public Object cacheDeptAdd(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出第一個引數
        Dept object = (Dept) joinPoint.getArgs()[0];
        Boolean res = (Boolean) joinPoint.proceed();
        if (res) {
            CACHE_CONTAINER.put(CACHE_DEPT_PROFIX + object.getId(), object);
        }
        return res;
    }

    /**
     * 查詢切入
     * 
     * @throws Throwable
     */
    @Around(value = POINTCUT_DEPT_GET)
    public Object cacheDeptGet(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出第一個引數
        Integer object = (Integer) joinPoint.getArgs()[0];
        // 從快取裡面取
        Object res1 = CACHE_CONTAINER.get(CACHE_DEPT_PROFIX + object);
        if (res1 != null) {
            log.info("已從快取裡面找到部門物件" + CACHE_DEPT_PROFIX + object);
            return res1;
        } else {
            Dept res2 = (Dept) joinPoint.proceed();
            CACHE_CONTAINER.put(CACHE_DEPT_PROFIX + res2.getId(), res2);
            log.info("未從快取裡面找到部門物件,去資料庫查詢並放到快取"+CACHE_DEPT_PROFIX+res2.getId());
            return res2;
        }
    }

    /**
     * 更新切入
     * 
     * @throws Throwable
     */
    @Around(value = POINTCUT_DEPT_UPDATE)
    public Object cacheDeptUpdate(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出第一個引數
        Dept deptVo = (Dept) joinPoint.getArgs()[0];
        Boolean isSuccess = (Boolean) joinPoint.proceed();
        if (isSuccess) {
            Dept dept = (Dept) CACHE_CONTAINER.get(CACHE_DEPT_PROFIX + deptVo.getId());
            if (null == dept) {
                dept = new Dept();
            }
            BeanUtils.copyProperties(deptVo, dept);
            log.info("部門物件快取已更新" + CACHE_DEPT_PROFIX + deptVo.getId());
            CACHE_CONTAINER.put(CACHE_DEPT_PROFIX + dept.getId(), dept);
        }
        return isSuccess;
    }

    /**
     * 刪除切入
     * 
     * @throws Throwable
     */
    @Around(value = POINTCUT_DEPT_DELETE)
    public Object cacheDeptDelete(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出第一個引數
        Integer id = (Integer) joinPoint.getArgs()[0];
        Boolean isSuccess = (Boolean) joinPoint.proceed();
        if (isSuccess) {
            // 刪除快取
            CACHE_CONTAINER.remove(CACHE_DEPT_PROFIX + id);
            log.info("部門物件快取已刪除" + CACHE_DEPT_PROFIX + id);
        }
        return isSuccess;
    }

    // 宣告切面表示式
    private static final String POINTCUT_USER_UPDATE = "execution(* com.sxt.sys.service.impl.UserServiceImpl.updateById(..))";
    private static final String POINTCUT_USER_ADD = "execution(* com.sxt.sys.service.impl.UserServiceImpl.save(..))";
    private static final String POINTCUT_USER_GET = "execution(* com.sxt.sys.service.impl.UserServiceImpl.getById(..))";
    private static final String POINTCUT_USER_DELETE = "execution(* com.sxt.sys.service.impl.UserServiceImpl.removeById(..))";

    private static final String CACHE_USER_PROFIX = "user:";

    /**
     * 使用者新增切入
     * 
     * @throws Throwable
     */
    @Around(value = POINTCUT_USER_ADD)
    public Object cacheUserAdd(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出第一個引數
        User object = (User) joinPoint.getArgs()[0];
        Boolean res = (Boolean) joinPoint.proceed();
        if (res) {
            CACHE_CONTAINER.put(CACHE_USER_PROFIX + object.getId(), object);
        }
        return res;
    }

    /**
     * 查詢切入
     * 
     * @throws Throwable
     */
    @Around(value = POINTCUT_USER_GET)
    public Object cacheUserGet(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出第一個引數
        Integer object = (Integer) joinPoint.getArgs()[0];
        // 從快取裡面取
        Object res1 = CACHE_CONTAINER.get(CACHE_USER_PROFIX + object);
        if (res1 != null) {
            log.info("已從快取裡面找到使用者物件" + CACHE_USER_PROFIX + object);
            return res1;
        } else {
            User res2 = (User) joinPoint.proceed();
            CACHE_CONTAINER.put(CACHE_USER_PROFIX + res2.getId(), res2);
            log.info("未從快取裡面找到使用者物件,去資料庫查詢並放到快取"+CACHE_USER_PROFIX+res2.getId());
            return res2;
        }
    }

    /**
     * 更新切入
     * 
     * @throws Throwable
     */
    @Around(value = POINTCUT_USER_UPDATE)
    public Object cacheUserUpdate(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出第一個引數
        User userVo = (User) joinPoint.getArgs()[0];
        Boolean isSuccess = (Boolean) joinPoint.proceed();
        if (isSuccess) {
            User user = (User) CACHE_CONTAINER.get(CACHE_USER_PROFIX + userVo.getId());
            if (null == user) {
                user = new User();
            }
            BeanUtils.copyProperties(userVo, user);
            log.info("使用者物件快取已更新" + CACHE_USER_PROFIX + userVo.getId());
            CACHE_CONTAINER.put(CACHE_USER_PROFIX + user.getId(), user);
        }
        return isSuccess;
    }

    /**
     * 刪除切入
     * 
     * @throws Throwable
     */
    @Around(value = POINTCUT_USER_DELETE)
    public Object cacheUserDelete(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出第一個引數
        Integer id = (Integer) joinPoint.getArgs()[0];
        Boolean isSuccess = (Boolean) joinPoint.proceed();
        if (isSuccess) {
            // 刪除快取
            CACHE_CONTAINER.remove(CACHE_USER_PROFIX + id);
            log.info("使用者物件快取已刪除" + CACHE_USER_PROFIX + id);
        }
        return isSuccess;
    }

}

第三

package com.sxt.sys.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sxt.sys.cache.CachePool;
import com.sxt.sys.common.CacheBean;
import com.sxt.sys.common.DataGridView;
import com.sxt.sys.common.ResultObj;

/**
 * 快取管理控制器
 * @author LJH
 *
 */
@RestController
@RequestMapping("cache")
public class CacheController {

    public static volatile Map<String, Object> CACHE_CONTAINER = CachePool.CACHE_CONTAINER;
    
    /**
     * 查詢所有快取
     */
    @RequestMapping("loadAllCache")
    public DataGridView loadAllCache() {
        List<CacheBean> list=new ArrayList<>();
        
        Set<Entry<String, Object>> entrySet = CACHE_CONTAINER.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            list.add(new CacheBean(entry.getKey(), entry.getValue()));
        }
        return new DataGridView(list);
    }
    
    /**
     * 刪除快取
     */
    @RequestMapping("deleteCache")
    public ResultObj deleteCache(String key) {
        CachePool.removeCacheByKey(key);
        return ResultObj.DELETE_SUCCESS;
    }
    
    /**
     * 清空快取
     */
    @RequestMapping("removeAllCache")
    public ResultObj removeAllCache() {
        CachePool.removeAll();
        return ResultObj.DELETE_SUCCESS;
    }
    /**
     * 同步快取
     */
    @RequestMapping("syncCache")
    public ResultObj syncCache() {
        CachePool.syncData();
        return ResultObj.OPERATE_SUCCESS;
    }
    
    
    
    
    
}