我正在尝试在 Java 和 .Net 之间共享存储在 couchbase memcached 存储桶中的数据。
我能够在 .Net 中读取 Java 中的字符串集,但每当我尝试在 Java 中读取 .Net 中的字符串集时,结果都是 Null。
那么是否可以在 couchbase 服务器的 memcache 存储桶中的 .Net 和 Java 之间交换数据。
最佳答案
谢谢你的回复,我已经明白了。
.NET 能够读取 Java 中设置的字符串的原因是,如果 enyimMemcached 库无法识别该标志,则它会将缓存项解释为字符串。
因此,为了能够读取 Java 中的字符串,我只是通过扩展 SpyObject 来创建自己的自定义转码器并将其设置为忽略该标志。然后我通过像这样的 get 调用传递自定义转码器,
_obj = GetMemcachedClient().get(key, new StringTranscoder())
我的 StringTranscoder 类看起来像这样,
/**
* Copyright (C) 2006-2009 Dustin Sallings
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
* IN THE SOFTWARE.
*/
package cachingjavatestapp;
import java.io.IOException;
import net.spy.memcached.CachedData;
import net.spy.memcached.compat.SpyObject;
import net.spy.memcached.transcoders.Transcoder;
import net.spy.memcached.transcoders.TranscoderUtils;
/**
* Transcoder that serializes and unserializes longs.
*/
public final class StringTranscoder extends SpyObject implements
Transcoder<String> {
private static final int FLAGS = 0;
public boolean asyncDecode(CachedData d) {
return false;
}
public CachedData encode(java.lang.String l) {
try{
return new CachedData(FLAGS, l.getBytes("UTF-8"), getMaxSize());
}
catch (Exception e){
return null;
}
}
public String decode(CachedData d) {
try{
return new String(d.getData(), "UTF-8");
}catch(Exception e){
return null;
}
}
public int getMaxSize() {
return CachedData.MAX_SIZE;
}
}
为了能够在.NET和Java之间交换数据。我只是使用 json.net 库和 gson 库来序列化对象,并将 json 字符串传递到 memcached,在 memcached 中将其作为字符串拾取,然后使用 json 库进行反序列化。
问候,
关于java - Couchbase 的 memcached 实现中 Java 和 .Net 之间的数据共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10887353/