• oscache使用经历


      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.inspur.chinanet.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 wulinfeng
     * @version C10 2018年3月28日
     * @since SDP V300R003C10
     */
    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);
            }
        }
        
        /**
         * 获取命中率
         *
         * @author wulinfeng
         * @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("wulinfeng");
                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.inspur.chinanet.point.cache.OsCache get
    警告: null
    三月 28, 2018 9:12:48 下午 com.inspur.chinanet.point.App main
    信息: no user.
    三月 28, 2018 9:12:48 下午 com.inspur.chinanet.point.App main
    信息: User [name=wulinfeng, sex=1, age=34]
  • 相关阅读:
    EAX、ECX、EDX、EBX寄存器的作用
    MFC VS2005 添加Override 和 Message
    ActiveX添加测试工程, 出现的问题[非选择性参数][找不到成员]
    两种应该掌握的排序方法--------2.quick Sort
    关于I/O的那点事
    整理一下 编码、解码库
    VC一些经验系列: 《分享泄漏检测工具:内存、DC、GDI、Handle... 》
    golang安装卸载 linux+windows+raspberryPI 平台
    (转)如何正确使用C++多重继承
    单播、多播(也称组播)、广播
  • 原文地址:https://www.cnblogs.com/wuxun1997/p/8666357.html
Copyright © 2020-2023  润新知