2015-04-15 84 views
0

我正在將我的Java代碼從Riak Client 1.4遷移到Riak Client 2.0。確定衝突解決期間RiakObject的位置

我在Riak 2.0中存儲了BinaryValue,封裝在RiakObject中。我需要提供自己的ConflictResolver來處理兄弟姐妹,但爲了做到這一點,我需要提取其他數據。這些數據來源於存儲對象的關鍵字。

在Riak 1.4中,我使用IRiakObject,它暴露getKey()。 Riak 2.0的RiakObject不提供此功能。

ConflictResolver.resolve(List<RiakObject> siblings)期間如何確定對象的Location(特別是關鍵)?

回答

2

不知道這是最好的方法,但它似乎工作:

  1. 創建一個POJO作爲二進制數據的容器。註釋一String@RiakKey

    public class Chunk { 
    
        @RiakKey 
        public String chunkId; 
    
        public byte[] data; 
    } 
    
  2. 創建一個自定義轉換器:

    import com.basho.riak.client.api.convert.ConversionException; 
    import com.basho.riak.client.api.convert.Converter; 
    import com.basho.riak.client.core.util.BinaryValue; 
    public class ChunkConverter extends Converter<Chunk> { 
    
        public ChunkConverter() { 
         super(Chunk.class); 
        } 
    
        public Chunk toDomain(BinaryValue val, String contentType) throws ConversionException { 
         Chunk chunk = newDomainInstance(); 
         chunk.data = val.getValue(); 
        } 
    
        public ContentAndType fromDomain(Chunk chunk) throws ConversionException { 
         return new ContentAndType(BinaryValue.unsafeCreate(chunk.data), "application/octet-stream"); 
        } 
    } 
    
  3. #1寄存器從#2的轉換器類:

    ConverterFactory.getInstance().registerConverterForClass(Chunk.class, new ChunkConverter()); 
    
  4. 創建來自#1的類的衝突解決器:

    public class ChunkConflictResolver implements ConflictResolver<Chunk> { 
    
        public Chunk resolve(List<Chunk> siblings) throws UnresolvedConflictException { 
         if (siblings == null) { 
          return null; 
         } 
         Chunk oneChunk = siblings.get(0); 
         // finally, the key! 
         String key = oneChunk.chunkId; 
         ... 
        } 
    } 
    
  5. 註冊從#4的新的衝突分解器的類從#1:

    ConflictResolverFactory.getInstance().registerConflictResolver(Chunk.class, new ChunkResolver()); 
    
  6. 當獲取從了Riak對象,指定從#1的類類型的值:

    Location loc = new Location(...); 
    FetchValue op = new FetchValue.Builder(loc).build(); 
    Chunk chunk = riakClient.execute(op).getValue(Chunk.class); 
    

在轉換過程中,傳輸對象的上下文,觀察annotations。自定義轉換器只需要傳輸數據的數值部分。