2013-03-16 45 views
0

我目前正在研究一個項目,要求我們存儲和接收來自服務器的食譜。食譜以json格式存儲在服務器ip + an id中。我一直在考慮創建一個可以保證在我們提交的兩個食譜之間不會重疊的ID的好方法。是否有一種標準的例外方式來創建這些ID,還是僅存儲一個最大ID的int保持軌跡並拉動每當有人想要存儲配方服務器端時更好?爲服務器端存儲創建ID的好方法?

由於提前,
優雅

public void addRecipe(Recipe recipe, String URL) throws IllegalStateException,  IOException{ 
    // TODO Implement the server-side ID tracking 
    //int id = getID(); 
    //recipe.setId(id); 
    HttpPost httpPost = new HttpPost(URL+recipe.getId()); 
    StringEntity stringEntity = null; 
    try { 
     stringEntity = new StringEntity(gson.toJson(recipe)); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    httpPost.setHeader("Accept","application/json"); 

    httpPost.setEntity(stringEntity); 
    HttpResponse response = null; 
    response = httpclient.execute(httpPost); 

    //  String status = response.getStatusLine().toString(); 
    //  System.out.println(status); 
    HttpEntity entity = response.getEntity(); 

    try { 
     // May need if statement, check isStreaming(); 
     entity.consumeContent(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    //May possibly need to deallocate more resources here. No 4.0 implementation of releaseconnection(); 
} 

也許這個代碼將有助於?這是我將食譜存儲在服務器上的方式。

+3

您的數據如何存儲? SQL db中的'autoincrement'列可以解決這個問題,例如 – 2013-03-16 04:41:49

+0

我不完全確定服務器端是爲我們設置的,我們只需要從中拉出並搜索,但我相信它是elasticsearch?如果這是有道理的? – Classtronaut 2013-03-16 04:48:09

+1

我想我們需要看到一些代碼和更多的上下文來幫助你。 – 2013-03-16 04:49:44

回答

0

所有數據庫供應商都支持某種(代理)ID生成機制。

如果您將對象存儲在數據庫中,則可以使用它。

如果您將對象存儲在LDAP中,則可以將節點DN用於此目的。

另一種選擇是使用一些社會保障(壞主意,但只是爲了解釋性質)的自然標識符,例如護照號碼,汽車的車牌號碼或它們的組合來唯一標識您的對象。

你不一定要使用某種代理(實際上是數字類型)Id。

人們經常會忘記自然主鍵,但它們確實很有幫助。

在你的情況下,它可能是服務器IP +時間戳,當食譜發佈。

但是兩臺服務器可以發佈相同的配方。 你會如何區分它們?

你會對待他們是否平等?

你是爲你的對象定義身份的人。

這取決於您的業務需求。

0

如果你不介意用java生成一個,你可以使用UUID如下:

UUID identifier = UUID.fromString(gson.toJson(recipe)); 
// use Strings as your id field 
String uuidUniqueId = identifier.toString(); 

不過,我強烈建議讓你的數據庫處理ID生成。畢竟,數據庫比我們在StackOverflow(或者Oracle的優秀人士)更好地知道如何優化對象的存儲。

相關問題