2017-11-28 4 views
0

저는 RIAK KV를 처음 접했습니다. 저는 실제로 대학에서 그것을 배우고 RIAK 클러스터에 5000 개의 데이터 세트를 저장하는 Java 코드를 작성해야합니다. 그래서 코드를 작성하기 시작했습니다 :메시지가 누락 된 이유는 무엇입니까? 어떻게 해결할 수 있습니까?

package main; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Collection; 
import java.util.Random; 
import java.util.Scanner; 

import org.w3c.dom.NameList; 

public class Product { 
    String artikelnummer; 
    String name; 
    String color; 
    Integer price; 
    String picture; 
    Integer max = 999; 
    String filepath = "./assets/products.txt"; 
    ArrayList<String> productNames; 

    public Product() throws FileNotFoundException{ 
     productNames = readFile(filepath); 
     name = randomName(); 
     color = randomColor(); 
     price = randomPrice(max); 
     picture = randomPic(); 
    } 

    private String randomPic() { 
     String[] picNames = {"ikea0.jpg","ikea1.jpg","ikea2.jpg","ikea3.jpg","ikea4.jpg","ikea5.jpg","ikea6.jpg","ikea7.jpg","ikea8.jpg","ikea9.jpg"}; 
     Random randPicIndex = new Random(); 
     int randomPicIndex = randPicIndex.nextInt(9); 
     return picNames[randomPicIndex]; 
    } 

    public Integer randomPrice(int max){ 
     Random rand = new Random(); 

     int randomNum = rand.nextInt(max); 
     price = randomNum; 
     return price; 
    } 

    public String randomColor(){ 
     String[] colorArray = {"blue","red","yellow","magenta","green","black","white","cyan","purple","brown"}; 
     Random randIndex = new Random(); 
     int randomIndex = randIndex.nextInt(10); 
     int i = randomIndex; 
     color = colorArray[i]; 
     return color; 
    } 

    public String randomName(){ 
     Random randomName = new Random(); 
     name = productNames.get(randomName.nextInt(productNames.size())); 
     return name; 
    } 

    public ArrayList<String> readFile(String filepath) throws FileNotFoundException { 
     Scanner scanner = new Scanner(new File(filepath)); 
     ArrayList<String> nameList = new ArrayList<String>(); 
     while (scanner.hasNextLine()){ 
      nameList.add(scanner.nextLine()); 
     } 
     scanner.close(); 
     return nameList; 
    } 

    //Class for testing purposes 
    public void printProduct(){ 
     System.out.println("Produktdatenblatt: Artikelnummer --> "+ artikelnummer + " " + name + " mit Farbe: " + color + " mit dem Preis: " + price + " ein Bild --> " + picture); 
     System.out.println("Hat funktioniert!!!"); 
    } 
} 

위 제품 클래스가 포함 된 코드를 볼 수 있습니다. 이것에 대해

RiakClient [email protected] 
RiakObjekt RiakObject{contentType: application/octet-stream, value: null, riakIndexes: null, links: null, userMeta: null, vtag: null, isDeleted: false, isModified: false, vclock: null, lastModified: 0} 
Bucket {type: default, bucket: products} 
Location {namespace: {type: default, bucket: products}, key: 1} 

Exception in thread "main" shaded.com.google.protobuf.UninitializedMessageException: Message missing required fields: value 
at shaded.com.google.protobuf.AbstractMessage$Builder.newUninitializedMessageException(AbstractMessage.java:372) 
at shaded.com.basho.riak.protobuf.RiakKvPB$RpbContent$Builder.build(RiakKvPB.java:18352) 
at com.basho.riak.client.core.converters.RiakObjectConverter.convert(RiakObjectConverter.java:198) 
at com.basho.riak.client.core.operations.StoreOperation$Builder.withContent(StoreOperation.java:158) 
at com.basho.riak.client.api.commands.kv.StoreValue.buildCoreOperation(StoreValue.java:151) 
at com.basho.riak.client.api.commands.kv.StoreValue.buildCoreOperation(StoreValue.java:72) 
at com.basho.riak.client.api.GenericRiakCommand.executeAsync(GenericRiakCommand.java:41) 
at com.basho.riak.client.api.commands.kv.StoreValue.executeAsync(StoreValue.java:112) 
at com.basho.riak.client.api.RiakCommand.execute(RiakCommand.java:91) 
at com.basho.riak.client.api.RiakClient.execute(RiakClient.java:355) 
at main.ProductRiakCluster.main(ProductRiakCluster.java:49) 

내 생각 : 내가 생성

package main; 
import io.netty.util.internal.shaded.org.jctools.queues.MessagePassingQueue.WaitStrategy; 
import java.io.FileNotFoundException; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 
import java.util.Collection; 
import java.util.concurrent.ExecutionException; 
import com.basho.riak.client.api.RiakClient; 
import com.basho.riak.client.api.annotations.RiakKey; 
import com.basho.riak.client.api.annotations.RiakLinks; 
import com.basho.riak.client.api.commands.kv.StoreValue; 
import com.basho.riak.client.core.RiakCluster; 
import com.basho.riak.client.core.RiakNode; 
import com.basho.riak.client.core.query.Location; 
import com.basho.riak.client.core.query.Namespace; 
import com.basho.riak.client.core.query.RiakObject; 
import com.basho.riak.client.core.query.links.RiakLink; 
import com.basho.riak.client.core.util.BinaryValue; 

public class ProductRiakCluster { 
    static String artikelnummer; 

    public static void main(String args[]) throws FileNotFoundException, UnknownHostException, ExecutionException, InterruptedException { 
     System.out.println("main-method started..."); 
     System.out.println("Starting create RiakCluster..."); 

     for (int i = 5000; i > 0; i--) { 
      dataGenerator(i); 

      RiakClient client = RiakClient.newClient(8087, "127.0.0.1"); 
      System.out.println("RiakClient " + client); 

      RiakObject riakObj = new RiakObject(); 
      System.out.println("RiakObjekt " + riakObj); 

      Namespace productsBucket = new Namespace("products"); 
      System.out.println("Bucket " + productsBucket); 

      Location productObjectLocation = new Location(productsBucket, artikelnummer); 
      System.out.println("Location " + productObjectLocation); 

      StoreValue storeP = new StoreValue.Builder(riakObj).withLocation(productObjectLocation).build(); 
      StoreValue.Response response = client.execute(storeP); 

      client.shutdown(); 
     } 
     System.out.println("RiakCluster setup finished..."); 
    } 

    public static class ProductPojo { 
     @RiakKey 
     public String artikelnummer; 
     public String name; 
     public String color; 
     public Integer price; 

     @RiakLinks 
     public Collection <RiakLink> picture = new ArrayList <RiakLink>(); 
    } 

    private static void dataGenerator(int i) { 
     System.out.println("Started DataGenerator..."); 

     try { 
      artikelnummer = String.valueOf(i); 
      generateRandomProduct(artikelnummer); 

     } catch (FileNotFoundException e) { 
      System.out.println("File not found..."); 
      e.printStackTrace(); 
     } 
    } 

    private static void generateRandomProduct(String artikelnummer) throws FileNotFoundException { 
     System.out.println("Method <generateRandomProduct> is running..." + artikelnummer); 

     Product product = new Product(); 
     ProductPojo propo = new ProductPojo(); 

     propo.artikelnummer = artikelnummer; 
     propo.name = product.name; 
     propo.color = product.color; 
     propo.price = product.price; 
     propo.picture.add(new RiakLink("pictures", product.picture, "Produktbild")); 

     product.printProduct(); 
    } 
} 

나는 다음과 같은 오류가 발생이 프로그램을 시작한 후 : 내가 다음 쓴 무작위로 500 개 제품을 생성하고 릭의 KV 데이터베이스에이 제품을 저장하려면 "artikelnummer"이지만 Pojo 클래스에서는 발생하지 않으므로 Pojo에는 null 값이 있습니다. 하지만이 문제를 해결하는 방법에 대한 해결책이 없습니다.

+2

_ 코드가 이해하기 어렵지 않기를 바랍니다 _ - 그렇지 않습니다. 그러나 읽는 것은 어렵습니다. 잠시 시간을내어 [Minimal, Complete, Verifiable Examples] (http://stackoverflow.com/help/mcve)에 대해 읽어보십시오. – Clijsters

+0

힐을 조금 개선하는 데 도움을 주셔서 감사합니다 :) – ElmoAll

+0

@ 엘모 아무런 문제가 없지만 기사를 읽으십시오. 왜냐하면 대부분의 '수입'이 코드를 이해하는 데 필요하지 않다고 생각하기 때문입니다. Btw. 방금 Java Beautifier에 넣었습니다.) – Hille

답변

1

문제는 RiakObject에 아무 것도 전달하지 않는다는 것입니다.

생성 된 ProductPojo의 인스턴스를 반환하고 변수에 저장합니다 (예 : productToSave). 불행하게도, 보조 노트로

RiakObject riakObj = new RiakObject(); 
riakObj.setValue(BinaryValue.create(productToSave)); 

, 코드가 몇 가지 프로그래밍 문제를 앓고 :

그런 다음 중 하나 new StoreValue.Builder(productToSave) 전화하거나 다음과 같이 RiakObject를 사용합니다. 예를 들어 정적 멤버를 통해 메소드간에 데이터를 교환하는 것은 좋지 않습니다. 또한 필요할 때마다 클라이언트를 생성하고 종료 할 필요가 없기 때문에 하나의 인스턴스를 모든 쿼리에 재사용 할 수 있습니다.

+0

당신의 솔루션은 많은 도움이되었습니다. 언급했듯이 많은 프로그래밍 문제가 있습니다. 잠깐 고쳐서 전체 프로그램을 마친 후 단 하나의 인스턴스와 종료를 만듭니다. – ElmoAll

관련 문제