缓存

为了不过多依赖环境,框架自带基于springCache默认实现了两个缓存

  • ehcache
  • redis

配置

application.yml

spring:
    # ehcache 缓存
    cache:
        type: ehcache
        ehcache:
            config: classpath:cool/cache/ehcache.xml
    # redis 缓存
    #  cache:
    #    type: redis
    #  redis:
    #    host: 127.0.0.1
    #    port: 6379
    #    database: 0
    #    password:

TIP

可以选择你想使用的缓存,性能要求比较高或有分布式部署需求的建议配置成 redis

使用

原生springCacheopen in new window方式

package com.cooljs.modules.demo.service.impl;

import com.cooljs.modules.demo.service.DemoCacheService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@CacheConfig(cacheNames = {"sys"})
@Service
public class DemoCacheServiceImpl implements DemoCacheService {
    @Cacheable(key = "targetClass + methodName +#p0")
    @Override
    public Object test(String id) {
        System.out.println("我被调用了");
        return "我被缓存了";
    }
}

框架特有的通用工具类,CoolCache

package com.cooljs.modules.demo.service.impl;

import com.cooljs.core.cache.CoolCache;
import com.cooljs.modules.demo.service.DemoCacheService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class DemoCacheServiceImpl implements DemoCacheService {
    @Resource
    CoolCache coolCache;

    @Override
    public Object test(String id) {
        coolCache.set("a", 1);
        return coolCache.get("a", Integer.class);
    }
}
Last Updated: