首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 專案整合 Neo4j 圖資料庫:嵌入模式與 REST 客戶端雙模式完整指南

     編輯:Java 相關知識

前言

Neo4j 以原生圖儲存著稱,擅長遍歷與關聯查詢。本文示範在 Java 專案中以嵌入模式與REST 客戶端模式兩種方式接入 Neo4j。

模式一:Maven 嵌入模式

1. 依賴配置


    org.neo4j
    neo4j
    1.9.4

2. 設定檔 neo4j.properties

# 記憶體映射、自動索引、線上備份、HA 叢集等設定...
keep_logical_logs=true
online_backup_enabled=true
# ha.server_id=1
# ha.coordinators=localhost:2181

3. Java 程式碼

public class Learn1 {
    private static final String DB_PATH = "target/neo4j-hello-db";
    private GraphDatabaseService graphDb;
    private Node firstNode, secondNode;
    private Relationship relationship;

    private enum RelTypes implements RelationshipType { KNOWS }

    public static void main(String[] args) {
        Learn1 app = new Learn1();
        app.createDb();
        app.removeData();
        app.shutDown();
    }

    void createDb() {
        clearDb();
        graphDb = new GraphDatabaseFactory()
            .newEmbeddedDatabaseBuilder("target/database/learn1")
            .loadPropertiesFromFile(getClass().getResource("/").getPath() + "neo4j.properties")
            .newGraphDatabase();
        registerShutdownHook(graphDb);

        try (Transaction tx = graphDb.beginTx()) {
            firstNode = graphDb.createNode();
            firstNode.setProperty("message", "Hello, ");
            secondNode = graphDb.createNode();
            secondNode.setProperty("message", "World!");
            relationship = firstNode.createRelationshipTo(secondNode, RelTypes.KNOWS);
            relationship.setProperty("message", "brave Neo4j ");
            System.out.print(firstNode.getProperty("message"));
            System.out.print(relationship.getProperty("message"));
            System.out.print(secondNode.getProperty("message"));
            tx.success();
        }
    }

    void removeData() {
        try (Transaction tx = graphDb.beginTx()) {
            firstNode.getSingleRelationship(RelTypes.KNOWS, Direction.OUTGOING).delete();
            firstNode.delete(); secondNode.delete();
            tx.success();
        }
    }

    void shutDown() { graphDb.shutdown(); }

    private void clearDb() {
        try { FileUtils.deleteRecursively(new File(DB_PATH)); }
        catch (IOException e) { throw new RuntimeException(e); }
    }

    private static void registerShutdownHook(GraphDatabaseService db) {
        Runtime.getRuntime().addShutdownHook(new Thread(db::shutdown));
    }
}

模式二:REST 客戶端模式(Neo4j Server)

1. 啟動 Server

下載 Neo4j 社群版,解壓後 bin/neo4j start,管理介面 https://localhost:7474。

2. Maven 依賴

com.sun.jerseyjersey-client1.17
com.sun.jerseyjersey-json1.17

3. Jersey 客戶端程式碼

public class Learn1Rest {
    private static final String ROOT = "https://localhost:7474/db/data/";

    public static void main(String[] args) {
        Learn1Rest client = new Learn1Rest();
        URI n1 = client.createNode();
        client.addProperty(n1, "name", "Joe Strummer");
        URI n2 = client.createNode();
        client.addProperty(n2, "band", "The Clash");
    }

    URI createNode() {
        WebResource r = Client.create().resource(ROOT + "node");
        ClientResponse resp = r.accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_JSON).entity("{}").post(ClientResponse.class);
        System.out.printf("POST [%s] status %d location %s%n", ROOT + "node", resp.getStatus(), resp.getLocation());
        resp.close();
        return resp.getLocation();
    }

    void addProperty(URI nodeUri, String key, String val) {
        WebResource r = Client.create().resource(nodeUri + "/properties/" + key);
        ClientResponse resp = r.accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_JSON).entity("\"" + val + "\"").put(ClientResponse.class);
        System.out.printf("PUT [%s] status %d%n", nodeUri + "/properties/" + key, resp.getStatus());
        resp.close();
    }
}

關鍵差異比較

維度嵌入模式REST 模式
部署應用內進程獨立 Server 進程
效能極高(無網路開銷)有網路延遲
擴展性受限於單機記憶體支援叢集與水平擴展
適用場景單體應用、測試、資料量中小微服務、多語言、生產叢集
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved