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]

oscache使用经历的更多相关文章

  1. H5拍照应用开发经历的那些坑儿

    一.项目简介 1.1.项目背景:这是一个在移动终端创新应用的项目,用户在浏览器端(微信/手Q)即可完成与金秀贤的合影,希望通过这样一种趣味体验,引发用户的分享与转发的热潮. 1.2.系统要求:ios6 ...

  2. 记2016腾讯 TST 校招面试经历,电面、笔试写代码、技术面、hr面,共5轮

    (出处:http://www.cnblogs.com/linguanh/) 前序: 距离  2016 腾讯 TST 校招面试结束已经5天了,3月27日至今,目前还在等待消息.从投简历到两轮电面,再到被 ...

  3. 阿里提前批校招内推offer经历

    经过一个半月的阿里内推面试,今天终于收到了阿里的offer邮件 .阿里的内推面试一共有四轮,本人是7月19号投的内推邮件,8月28号收到了offer的邮件.首先本人谈谈内推的看法.内推是公司招聘人才的 ...

  4. Ubuntu服务器被黑经历(ElastichSearch漏洞)

    起因 最近我们的一台Ubuntu阿里云服务器一直提示有肉鸡行为,提示了好几天,开始并没有关注,然后连续几天后发现应该是个大问题啊.很可能服务被侵入了!!! 寻找线索 一开始我是完全懵逼的状态的,Lin ...

  5. CVTE实习求职经历

    今天,听到有好多同学最近要去面试CVTE这家企业,于是呢,准备将自己的经历写上来,给大家一个参考,希望能够大家一次帮助. 一.整体感觉 首先呢,先讲一下我个人对这家企业的整体感觉吧. 1. 第一次 对 ...

  6. geotrellis使用(七)记录一次惨痛的bug调试经历以及求DEM坡度实践

    眼看就要端午节了,屌丝还在写代码,话说过节也不给轻松,折腾了一天终于解决了一个BUG,并完成了老板安排的求DEM坡度的任务,那么就分两段来表. 一.BUG调试 首先记录一天的BUG调试,简单copy了 ...

  7. 淘宝web前端开发岗面试经历及感悟

    今天下午四点接到淘宝UED的面试电话,很突然,很激动.现在怀着淡淡的忧伤为之文以志一下. 1.自我介绍一下. 我xx时候毕业,在xx公司任xx职务,主要负责xx balabala.(怕公司同事听到,接 ...

  8. [分享] 很多人手机掉了,却不知道怎么找回来。LZ亲身经历讲述手机找回过程,申请加精!

    文章开头:(LZ文笔不好,以下全部是文字描述,懒得配图.因为有人说手机掉了,他们问我是怎么找回来的.所以想写这篇帖子.只不过前段时间忙,没时间.凑端午节给大家一些经验) 还是先谢谢被偷经历吧!5月22 ...

  9. iftop与dstat-一次网站故障分析经历

    一次网站分析与解决的经历,最后结果虽然很简单但是过程比较曲折.记录一下: 今天访问网站首页十分缓慢,页面半天都加载不出来.于是上服务器看看情况,通过top看到load和cpu以及磁盘io都很低,只能祭 ...

随机推荐

  1. HTTP响应代码集合

    用于表示临时响应并需要请求者执行操作才能继续的状态代码.代码说明100(继续)请求者应当继续提出请求.服务器返回此代码则意味着,服务器已收到了请求的第一部分,现正在等待接收其余部分. 101(切换协议 ...

  2. jQuery的序列化元素 serialize()方法 serializeArray()方法 param()方法

    当提交的表单元素较多时用serialize()方法,serialize()方法也是作用于一个jQuery的对象,它能够将DOM元素内容序列化为字符串,用于Ajax请求. serialize() 方法通 ...

  3. HDU 1159 Common Subsequence 动态规划

    2017-08-06 15:41:04 writer:pprp 刚开始学dp,集训的讲的很难,但是还是得自己看,从简单到难,慢慢来(如果哪里有错误欢迎各位大佬指正) 题意如下: 给两个字符串,找到其中 ...

  4. oracle,查看锁表

    (1)锁表查询的代码有以下的形式:select count(*) from v$locked_object;select * from v$locked_object;(2)查看哪个表被锁select ...

  5. Sql Server 中关于@@ERROR的一个小小误区

    我们经常写存储过程的时候会用到@@ERROR来判断执行是否成功,很久没有写复杂点的存储过程了,今天发现前段时间写的一个proc出现了bug,由于定义参数时,字符串长度设的有点短,导致传进来的值中间被截 ...

  6. 算法练习5---快速排序Java版

    基本思想:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成 ...

  7. TCP和Http的区别!(转) 真心有帮助!!!

    一.From:http://thisliy.javaeye.com/blog/710122 http://wenku.baidu.com/view/14a30d0102020740be1e9b84.h ...

  8. iOS自动化探索(五)自动化测试框架pytest - Assert断言的使用

    使用assert语句进行断言 pytest允许使用标准的python assert语法,用来校验expectation and value是否一致 代码演示: def func(): def test ...

  9. Flask 分页的简单用法 / flask_sqlalchemy /无刷新翻转页面(原创)

    flask_sqlalchemy对象提供分页方法 1. 后台views代码: from models import <table_name> #导入model的对象 @app.route( ...

  10. Struts07---访问servlet的API

    01.创建登录界面 <%@ page language="java" import="java.util.*" pageEncoding="UT ...