Redis缓存对象的实现原理

		</div>
		<div class="article-info-box">
			<div class="article-bar-top">
	
				<a class="follow-nickName" href="https://me.csdn.net/qq_43001609" target="_blank">liyuanwlly</a>
					<span class="read-count">阅读数:3</span>
									</div>
			<div class="operating">
													</div>
		</div>
	</div>
</div>
<article>
	<div id="article_content" class="article_content clearfix csdn-tracking-statistics" data-pid="blog" data-mod="popu_307" data-dsm="post" style="height: 1929px; overflow: hidden;">
							            <div class="markdown_views prism-atom-one-dark">
						<!-- flowchart 箭头图标 勿删 -->
						<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg>
						<div id="article_content" class="article_content clearfix csdn-tracking-statistics" style="height: 1929px; overflow: hidden;">
							            
					<div class="htmledit_views">
            <p>&nbsp; &nbsp; &nbsp; 截止到目前为止,在redis官方的文档和实现里面并没有针对object 对象缓存的方法,然而,在我们的实际开发需要中,在很多时候我们是需要进行对象缓存的,并且可以正确的读取出来! 在笔者正在开发的红包项目中,针对每天红包就需要使用的对象缓存,并可以随时修改缓存对象中的红包数量值等信息!那么具体实现呢?</p><p>&nbsp; &nbsp; &nbsp; &nbsp;在官方提供的方法中,我们找到了有这么一个操作方法:&nbsp;</p><p><span></span><span>      jedis.set(byte[], byte[])</span></p><p><span>      看这个方法,是进行字节码操作的,这让我们很容易想到在一些远程方法调用中,我们传递对象同样传递的是字节码,是不是可以参考呢?</span></p><p><span>     首先,既然需要对对象进行字节操作,即可写和可读的操作,为了保证这个原则,那么缓存对象需要实现Serializable 接口,进行序列化和反序列化!</span></p><p><span>     涉及到的知识点:</span></p><p><span>    1:   <span>Serializable  (接口,实现此接口的对象可以进行序列化)</span></span></p><p><span><span>     2:  </span></span><span>ByteArrayOutputStream,</span><span>ObjectOutputStream  对象转换为字节码输出流</span></p><p><span>   3: </span><span>ByteArrayInputStream  ,</span><span>ObjectInputStream   字节码转换为对象的输入流</span></p><p><span>  了解了如上三点知识后,我们就可以对对象进行缓存操作了!</span></p><p><span><span>示例代码如下,包括了对象缓存和List 对象数组缓存,需要声明的是,放入list数组中的对象同样需要实现Serializable 接口:</span></span></p><p><span><span></span></span></p><pre class="prettyprint"><span><strong>public class </strong></span>ObjectsTranscoder <span><strong>extends </strong></span>SerializeTranscoder {
<span style="color:#808000;">@SuppressWarnings</span>(<span style="color:#008000;"><strong>"unchecked"</strong></span>)
<span style="color:#808000;">@Override

  
  
  • 1
  • 2

public byte[] serialize(Object value) {

if (value == null) {

throw new NullPointerException(“Can’t serialize null”);

}

byte[] result = null;

ByteArrayOutputStream bos = null;

ObjectOutputStream os = null;

try {

bos = new ByteArrayOutputStream();

os = new ObjectOutputStream(bos);

os.writeObject(value);

os.close();

bos.close();

result = bos.toByteArray();

} catch (IOException e) {

throw new IllegalArgumentException(“Non-serializable object”, e);

} finally {

close(os);

close(bos);

}

return result;

}

<span style="color:#808000;">@SuppressWarnings</span>(<span style="color:#008000;"><strong>"unchecked"</strong></span>)
<span style="color:#808000;">@Override

  
  
  • 1
  • 2

public Object deserialize(byte[] in) {
Object result = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
result = is.readObject();
is.close();
bis.close();
}
} catch (IOException e) {
logger.error(String.format(“Caught IOException decoding %d bytes of data”,
in == null ? 0 : in.length) + e);
} catch (ClassNotFoundException e) {
logger.error(String.format(“Caught CNFE decoding %d bytes of data”,
in == null ? 0 : in.length) + e);
} finally {
close(is);
close(bis);
}
return result;
}
}

对象的转换示例如上代码:

数组缓存代码:

public class ListTranscoder<M extends Serializable> extends SerializeTranscoder {
<span style="color:#808000;">@SuppressWarnings</span>(<span style="color:#008000;"><strong>"unchecked"</strong></span>)
<span style="color:#000080;"><strong>public </strong></span>List&lt;<span style="color:#20999d;">M</span>&gt; deserialize(<span style="color:#000080;"><strong>byte</strong></span>[] in) {
    List&lt;<span style="color:#20999d;">M</span>&gt; list = <span style="color:#000080;"><strong>new </strong></span>ArrayList&lt;&gt;();
    ByteArrayInputStream bis = <span style="color:#000080;"><strong>null</strong></span>;
    ObjectInputStream is = <span style="color:#000080;"><strong>null</strong></span>;
    <span style="color:#000080;"><strong>try </strong></span>{
        <span style="color:#000080;"><strong>if </strong></span>(in != <span style="color:#000080;"><strong>null</strong></span>) {
            bis = <span style="color:#000080;"><strong>new </strong></span>ByteArrayInputStream(in);
            is = <span style="color:#000080;"><strong>new </strong></span>ObjectInputStream(bis);
            <span style="color:#000080;"><strong>while </strong></span>(<span style="color:#000080;"><strong>true</strong></span>) {
                <span style="color:#20999d;">M </span>m = (<span style="color:#20999d;">M</span>)is.readObject();
                <span style="color:#000080;"><strong>if </strong></span>(m == <span style="color:#000080;"><strong>null</strong></span>) {
                    <span style="color:#000080;"><strong>break</strong></span>;
                }
            list.add(m);

        }
        is.close();
        bis.close();
    }
} &lt;span style="color:#000080;"&gt;&lt;strong&gt;catch &lt;/strong&gt;&lt;/span&gt;(IOException e) {
    &lt;span style="color:#660e7a;"&gt;&lt;em&gt;logger&lt;/em&gt;&lt;/span&gt;.error(String.&lt;span style="font-style:italic;"&gt;format&lt;/span&gt;(&lt;span style="color:#008000;"&gt;&lt;strong&gt;"Caught IOException decoding %d bytes of data"&lt;/strong&gt;&lt;/span&gt;,
            in == &lt;span style="color:#000080;"&gt;&lt;strong&gt;null &lt;/strong&gt;&lt;/span&gt;? &lt;span style="color:#0000ff;"&gt;0 &lt;/span&gt;: in.&lt;span style="color:#660e7a;"&gt;&lt;strong&gt;length&lt;/strong&gt;&lt;/span&gt;) + e);
} &lt;span style="color:#000080;"&gt;&lt;strong&gt;catch &lt;/strong&gt;&lt;/span&gt;(ClassNotFoundException e) {
    &lt;span style="color:#660e7a;"&gt;&lt;em&gt;logger&lt;/em&gt;&lt;/span&gt;.error(String.&lt;span style="font-style:italic;"&gt;format&lt;/span&gt;(&lt;span style="color:#008000;"&gt;&lt;strong&gt;"Caught CNFE decoding %d bytes of data"&lt;/strong&gt;&lt;/span&gt;,
            in == &lt;span style="color:#000080;"&gt;&lt;strong&gt;null &lt;/strong&gt;&lt;/span&gt;? &lt;span style="color:#0000ff;"&gt;0 &lt;/span&gt;: in.&lt;span style="color:#660e7a;"&gt;&lt;strong&gt;length&lt;/strong&gt;&lt;/span&gt;) + e);
}  &lt;span style="color:#000080;"&gt;&lt;strong&gt;finally &lt;/strong&gt;&lt;/span&gt;{
    close(is);
    close(bis);
}

&lt;span style="color:#000080;"&gt;&lt;strong&gt;return  &lt;/strong&gt;&lt;/span&gt;list;

}

<span style=“color:#808000;”>@SuppressWarnings</span>(<span style=“color:#008000;”><strong>“unchecked”</strong></span>)
<span style=“color:#808000;”>@Override

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

public byte[] serialize(Object value) {

if (value == null)

throw new NullPointerException(“Can’t serialize null”);

    List&lt;<span style="color:#20999d;">M</span>&gt; values = (List&lt;<span style="color:#20999d;">M</span>&gt;) value;

    <span style="color:#000080;"><strong>byte</strong></span>[] results = <span style="color:#000080;"><strong>null</strong></span>;
    ByteArrayOutputStream bos = <span style="color:#000080;"><strong>null</strong></span>;
    ObjectOutputStream os = <span style="color:#000080;"><strong>null</strong></span>;

    <span style="color:#000080;"><strong>try </strong></span>{
        bos = <span style="color:#000080;"><strong>new </strong></span>ByteArrayOutputStream();
        os = <span style="color:#000080;"><strong>new </strong></span>ObjectOutputStream(bos);
        <span style="color:#000080;"><strong>for </strong></span>(<span style="color:#20999d;">M </span>m : values) {
            os.writeObject(m);
        }

        <span style="color:#808080;"><em>// os.writeObject(null);

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

os.close();
bos.close();
results = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException(“Non-serializable object”, e);
} finally {
close(os);
close(bos);
}

    <span style="color:#000080;"><strong>return </strong></span>results;
}

  
  
  • 1
  • 2

}

通过以上操作即可以实现对象的缓存和读取了!

虽然自己实现了,还是希望redis官方尽快提供对象的缓存操作吧!



        </div>
					<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-8cccb36679.css" rel="stylesheet">
            </div>
								<div class="hide-article-box text-center">
					<a class="btn" id="btn-readmore" data-track-view="{&quot;mod&quot;:&quot;popu_376&quot;,&quot;con&quot;:&quot;,https://blog.csdn.net/qq_43001609/article/details/82933474,&quot;}" data-track-click="{&quot;mod&quot;:&quot;popu_376&quot;,&quot;con&quot;:&quot;,https://blog.csdn.net/qq_43001609/article/details/82933474,&quot;}">阅读更多</a>
				</div>
				<script>
					(function(){
						function setArticleH(btnReadmore,posi){
							var winH = $(window).height();
							var articleBox = $("div.article_content");
							var artH = articleBox.height();
							if(artH > winH*posi){
								articleBox.css({
									'height':winH*posi+'px',
									'overflow':'hidden'
								})
								btnReadmore.click(function(){
									articleBox.removeAttr("style");
									$(this).parent().remove();
								})
							}else{
								btnReadmore.parent().remove();
							}
						}
						var btnReadmore = $("#btn-readmore");
						if(btnReadmore.length>0){
							if(currentUserName){
								setArticleH(btnReadmore,3);
							}else{
								setArticleH(btnReadmore,1.2);
							}
						}
					})()
				</script>
				</article>
还能输入1000个字符
</div>

memcached&redis等分布式缓存的实现原理

shaochenshuo shaochenshuo

01-21 4568

memcached&redis等分布式缓存的实现原理

DBAplus社群(陈科)
· 2015-12-13 07:00

12月9日,河狸家资深架构师…









redis缓存java对象




u012572955

u012572955




11-09




5668




Redis入门 – Jedis存储Java对象 -
(Java序列化为byte数组方式)

原文地址:http://alanland.iteye.com/admin/blogs/16…






<iframe width="852" height="60" scrolling="no" src="//pos.baidu.com/s?hei=60&amp;wid=852&amp;di=u3491668&amp;ltu=https%3A%2F%2Fblog.csdn.net%2Fqq_43001609%2Farticle%2Fdetails%2F82933474&amp;pss=1309x3193&amp;col=zh-CN&amp;dtm=HTML_POST&amp;chi=1&amp;cpl=12&amp;cja=false&amp;ltr=https%3A%2F%2Fwww.csdn.net%2Fnav%2Fnewarticles&amp;dri=0&amp;cdo=-1&amp;ccd=24&amp;cfv=0&amp;tcn=1538567780&amp;dai=1&amp;tlm=1538567779&amp;ps=2435x382&amp;pcs=1309x643&amp;par=1366x768&amp;dis=0&amp;ari=2&amp;cce=true&amp;prot=2&amp;tpr=1538567779601&amp;psr=1366x768&amp;ant=0&amp;cec=UTF-8&amp;dc=3&amp;pis=-1x-1&amp;drs=1&amp;exps=111000&amp;ti=Redis%E7%BC%93%E5%AD%98%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%20-%20qq_43001609%E7%9A%84%E5%8D%9A%E5%AE%A2%20-%20CSDN%E5%8D%9A%E5%AE%A2&amp;cmi=28"></iframe>

				<div class="recommend-item-box recommend-box-ident type_blog clearfix" data-track-view="{&quot;mod&quot;:&quot;popu_387&quot;,&quot;con&quot;:&quot;,https://blog.csdn.net/qq_17635843/article/details/78990681,BlogCommendFromQuerySearch_2,index_2&quot;}" data-track-click="{&quot;mod&quot;:&quot;popu_387&quot;,&quot;con&quot;:&quot;,https://blog.csdn.net/qq_17635843/article/details/78990681,BlogCommendFromQuerySearch_2,index_2&quot;}" data-flg="true">
	<a href="https://blog.csdn.net/qq_17635843/article/details/78990681" target="_blank" title="Redis缓存对象相关">
		<div class="content" style="width: 842px;">
			<h4 class="text-truncate oneline" style="width: 726px;">
					<em>Redis缓存</em><em>对象</em>相关				</h4>
			<div class="info-box d-flex align-content-center">
				<p class="avatar">
						<img src="https://avatar.csdn.net/5/6/7/3_qq_17635843.jpg" alt="qq_17635843" class="avatar-pic">
						<span class="namebox" style="left: -37.5px;">
							<span class="name">qq_17635843</span>
							<span class="triangle"></span>
						</span>
				</p>
				<p class="date-and-readNum">
					<span class="date hover-show">01-06</span>
					<span class="read-num hover-hide">
						<svg class="icon csdnc-yuedushu" aria-hidden="true">
							<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#csdnc-yuedushu"></use>
						</svg>
						540</span>
					</p>
				</div>
				<p class="content oneline" style="width: 842px;">
						1、想要使用redis先获得连接池对象,及JedisPool 

然后在配置生成连接池对象需要的参数咯
(1)你可以写一个参数实体类,再写一个bean注入到spring

@Component
@Co…









Java在redis中进行对象的缓存




qq_20989105

qq_20989105




01-26




2200




Java在redis中进行对象的缓存一般有两种方法,这里介绍序列化的方法,个人感觉比较方便,不需要转来转去。
1、首先,在存储的对象上实现序列化的接口

package com.cy.examp…









Redis缓存Object,List对象




leledodo

leledodo




10-14




4281




到目前为止(jedis-2.2.0.jar),在Jedis中其实并没有提供这样的API对对象,或者是List对象的直接缓存,即并没有如下类似的API

jedis.set(String key, Ob…









Redis分布式锁的原理、作用及实现(简单易懂)




IRhythm

IRhythm




08-31




32




转载地址:https://blog.csdn.net/l_bestcoder/article/details/79336986;(注:做了一些修改)。

一、什么是分布式锁?

要介绍分布式锁,首先要…













基于redis的缓存机制的思考和优化




qq_18860653

qq_18860653




02-06




1.7万




相对我们对于redis的使用场景都已经想当的熟悉。对于大量的数据,为了缓解接口(数据库)的压力,我们对查询的结果做了缓存的策略。一开始我们的思路是这样的。
1.执行查询
2.缓存中存在数据 -> 查询…









node使用redis缓存




a5799694

a5799694




12-14




1056




最近想知道node相关的缓存,就找到了redis
然后自己实现了node api数据的缓存
我先写了个模块,当做redis的链接对象的工厂
新建了redis_factory.js
var re…









redis 和Mysql 的一些 区别




qq_28018283

qq_28018283




05-24




1.9万




说 Redis 的缓存机制实现之前,我想先回顾一下 mysql

mysql 存储在哪儿呢?

以 windows 为例,mysql 的表和数据,存储在data 目录下frm ibd 后缀的文件中…









redis 缓存失效原理




u013530955

u013530955




07-05




2976




原文出处:点击打开链接

对于缓存失效,不同的缓存有不同的处理机制,可以说是大同中有小异,作者通过对Redis 文档与相关源码的仔细研读,为大家详细剖析了 Redis 的缓存过期/失效机制相关的技术…






博主推荐







换一批


PayneQin

关注 228篇文章

Sam哥哥

关注 173篇文章

Evankaka

关注 285篇文章



        <div class="recommend-loading-box">
            <img src="https://csdnimg.cn/release/phoenix/images/feedLoading.gif">
        </div>
        <div class="recommend-end-box">
            <p class="text-center">没有更多推荐了,<a href="https://blog.csdn.net/" class="c-blue c-blue-hover c-blue-focus">返回首页</a></p>
        </div>
    </div>
</main>

猜你喜欢

转载自blog.csdn.net/wangliang369/article/details/82933515