oscache使用经历

本文介绍了如何在Maven项目中使用OSCache作为对象缓存。首先,通过Maven引入OSCache依赖;接着配置oscache.properties,设置缓存容量、算法等参数;然后创建OsCache类实现缓存操作;最后,展示了一个使用缓存的主方法示例,包括获取、插入和删除缓存数据。
摘要由CSDN通过智能技术生成

  oscache作为一款老的本地缓存,应用场景主要有页面缓存和对象缓存。这里拿在maven项目中使用oscache作为对象缓存举例说明下用法:

  1、导入jar包

        <dependency>
            <groupId>opensymphony</groupId>
            <artifactId>oscache</artifactId>
            <version>2.4.1</version>
        </dependency>

  2、在resources目录下新增配置文件oscache.properties

# CACHE IN MEMORY
#
# If you want to disable memory caching, just uncomment this line.
#
cache.memory=true

# CACHE SIZE
#
# Default cache size in number of items. If a size is specified but not
# an algorithm, the cache algorithm used will be LRUCache.
#
cache.capacity=100000

# CACHE LISTENERS
#
# These hook OSCache events and perform various actions such as logging
# cache hits and misses, or broadcasting to other cache instances across a cluster.
# See the documentation for further information.
#

#                      com.opensymphony.oscache.extra.CacheEntryEventListenerImpl


# CACHE ALGORITHM
#
# Default cache algorithm to use. Note that in order to use an algorithm
# the cache size must also be specified. If the cache size is not specified,
# the cache algorithm will be Unlimited cache.
#
 #cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache
 cache.algorithm=com.opensymphony.oscache.base.algorithm.FIFOCache

# THREAD BLOCKING BEHAVIOR
#
# When a request is made for a stale cache entry, it is possible that another thread is already
# in the process of rebuilding that entry. This setting specifies how OSCache handles the
# subsequent 'non-building' threads. The default behaviour (cache.blocking=false) is to serve
# the old content to subsequent threads until the cache entry has been updated. This provides
# the best performance (at the cost of serving slightly stale data). When blocking is enabled,
# threads will instead block until the new cache entry is ready to be served. Once the new entry
# is put in the cache the blocked threads will be restarted and given the new entry.
# Note that even if blocking is disabled, when there is no stale data available to be served
# threads will block until the data is added to the cache by the thread that is responsible
# for building the data.
#
# cache.blocking=false

# JAVAGROUPS CLUSTER PROPERTIES
#
# Configuration properites for the JavaGroups clustering. Only one of these
# should be specified. Default values (as shown below) will be used if niether
# property is set. See the clustering documentation and the JavaGroups project
# (www.javagroups.com) for more information on these settings.
#
#cache.cluster.properties=UDP(singleton_name\=screenWidthAdapter;tos\=8;mcast_addr\=225.90.21.10;mcast_port\=50103;mcast_send_buf_size\=640K;mcast_recv_buf_size\=25M;ip_ttl\=32;loopback\=true;discard_incompatible_packets\=true;enable_bundling\=true;max_bundle_size\=64K;max_bundle_timeout\=30;enable_diagnostics\=true;thread_naming_pattern\=book;timer.num_threads\=4;thread_pool.enabled\=true;thread_pool.min_threads\=2;thread_pool.max_threads\=8;thread_pool.keep_alive_time\=5000;thread_pool.queue_enabled\=true;thread_pool.queue_max_size\=10000;thread_pool.rejection_policy\=discard;oob_thread_pool.enabled\=true;oob_thread_pool.min_threads\=1;oob_thread_pool.max_threads\=8;oob_thread_pool.keep_alive_time\=5000;oob_thread_pool.queue_enabled\=false;oob_thread_pool.queue_max_size\=100;oob_thread_pool.rejection_policy\=Run)\:PING(timeout\=2000;num_initial_members\=3)\:MERGE2(min_interval\=10000;max_interval\=30000)\:FD(timeout\=20000;max_tries\=9)\:FD_SOCK()\:FD_ALL()\:VERIFY_SUSPECT(timeout\=15000)\:BARRIER()\:pbcast.NAKACK(retransmit_timeout\=300,600,1200,2400,4800,9600,19200;use_mcast_xmit\=true;use_stats_for_retransmission\=true;xmit_history_max_size\=500;max_rebroadcast_timeout\=20000;discard_delivered_msgs\=false;gc_lag\=500;use_stats_for_retransmission\=false;exponential_backoff\=0)\:UNICAST(timeout\=300,600,1200,2400,4800,9600,19200)\:pbcast.STABLE(stability_delay\=1000;desired_avg_gossip\=20000;max_bytes\=1M)\:pbcast.GMS(join_timeout\=3000;print_local_addr\=true;view_bundling\=true)\:FC(max_credits\=500K;min_threshold\=0.20;ignore_synchronous_response\=true)\:FRAG2(frag_size\=60K)\:pbcast.STATE_TRANSFER()

  3、新增缓存类

package com.wlf.net.point.cache;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;

import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;
import com.opensymphony.oscache.web.filter.ExpiresRefreshPolicy;

/**
 * 本地缓存
 *
 * @author wulf
 * @since 2018年3月28日*/
public class OsCache extends GeneralCacheAdministrator
{
    
    private static final Logger LOG = Logger.getLogger("OsCache");
    
    /**
     * 序列化ID
     */
    private static final long serialVersionUID = -3814537980571610987L;
    
    // 缓存命中次数
    private AtomicLong hitCount = new AtomicLong(0L);
    
    // 总请求次数
    private AtomicLong reqCount = new AtomicLong(0L);
    
    // 命中率
    private double hitRate = 0D;
    
    private static final OsCache cache = new OsCache();
    
    /**
     * 单例
     */
    public static OsCache getInstance()
    {
        return cache;
    }
    
    /**
     * 从OSCACHE中获取原始缓存数据
     * 
     * @param key 缓存KEY值
     * @param refreshTime 失效时间,-1时为永久缓存
     * @return 原始缓存数据
     */
    public Object get(String key, int refreshTime)
    {
        reqCount.incrementAndGet();
        Object obj = null;
        try
        {
            obj = this.getFromCache(key, refreshTime);
            hitCount.incrementAndGet();
        }
        catch (NeedsRefreshException e)
        {
            this.cancelUpdate(key);
            LOG.warning(e.getMessage());
        }
        return obj;
    }
    
    /**
     * 从OSCACHE中获取原始缓存数据
     * 
     * @param key 缓存KEY值
     * @param value Object 内容对象
     * @param refreshTime 失效时间,-1时为永久缓存
     * @return 原始缓存数据
     */
    public void put(String key, Object value, int refreshTime)
    {
        if (refreshTime == -1)
        {
            this.putInCache(key, value);
        }
        else
        {
            this.putInCache(key, value, new ExpiresRefreshPolicy(refreshTime));
        }
    }
    
    /**
     * 从OSCACHE中删除缓存数据
     * 
     * @param key 缓存KEY值
     */
    public void remove(String key)
    {
        this.removeEntry(key);
    }
    
    /**
     * 从OSCACHE中删除所有缓存数据
     * 
     * @param date 预定删除时间
     */
    public void removeAll(Date date)
    {
        if (date == null)
        {
            this.flushAll();
        }
        else
        {
            this.flushAll(date);
        }
    }
    
    /**
     * 获取命中率
     *
     * @return
     */
    public double getHitRate()
    {
        if (reqCount.longValue() == 0L)
        {
            return 0;
        }
        
        hitRate = (double)hitCount.longValue() / reqCount.longValue();
        BigDecimal bd = new BigDecimal(hitRate);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        
        return bd.doubleValue();
    }
}

  4、使用缓存主方法

   public static void main(String[] args)
    {
        User user = (User)OsCache.getInstance().get("user_", -1);
        
        if(user != null)
        {
            LOG.info(user.toString());
        }
        else
        {
            LOG.info("no user.");
            user = new User();
            user.setName("wulf");
            user.setAge(34);
            user.setSex(1);
            OsCache.getInstance().put("user_", user, -1);
            user = (User)OsCache.getInstance().get("user_", -1);
            LOG.info(user.toString());
        }

  5、执行主方法结果

三月 28, 2018 9:12:48 下午 com.opensymphony.oscache.base.Config loadProperties
信息: OSCache: Getting properties from URL file:/E:/workspace/TeaPot/target/classes/oscache.properties for the default configuration
三月 28, 2018 9:12:48 下午 com.opensymphony.oscache.base.Config loadProperties
信息: OSCache: Properties read {cache.algorithm=com.opensymphony.oscache.base.algorithm.FIFOCache, cache.capacity=100000, cache.memory=true}
三月 28, 2018 9:12:48 下午 com.opensymphony.oscache.general.GeneralCacheAdministrator <init>
信息: Constructed GeneralCacheAdministrator()
三月 28, 2018 9:12:48 下午 com.opensymphony.oscache.general.GeneralCacheAdministrator createCache
信息: Creating new cache
三月 28, 2018 9:12:48 下午 com.wlf.net.point.cache.OsCache get
警告: null
三月 28, 2018 9:12:48 下午 com.wlf.net.point.App main
信息: no user.
三月 28, 2018 9:12:48 下午 com.wlf.net.point.App main
信息: User [name=wulf, sex=1, age=34]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>