今天看公司项目的源码,自己简单的实现一下
public static void add() throws SQLException {
// jdbc连接配置
String url = "jdbc:mysql://localhost:3306/canteen";
String user = "username";
String password = "password";
String indexSQL = "select * from Test";
long indexNum = 0;
List<Test> list = new ArrayList<>();
// 获取数据库连接
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement = con.prepareStatement(indexSQL);
// 获取结果集
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
// 组装对象
Test test = new Test();
test.id = resultSet.getInt("id");
test.title = resultSet.getString("title");
test.content = resultSet.getString("content");
test.addTime = resultSet.getTimestamp("addTime");
test.addTime = resultSet.getTimestamp("updateTime");
list.add(test);
}
if(list.size() > 0) {
indexNum += list.size();
BulkRequestBuilder bulkRequestBuilder = getClient().prepareBulk();
for(Test test : list) {
Logger.info(test.toString());
IndexRequest indexRequest = getClient().prepareIndex("test", "book", test.id.toString())
.setSource(gson.toJson(test))
.setParent(null)
.request();
bulkRequestBuilder.add(indexRequest);
BulkResponse bulkItemResponses = bulkRequestBuilder.setRefreshPolicy(WriteRequest.RefreshPolicy.NONE).execute().actionGet();
if(bulkItemResponses.hasFailures()) {
Logger.error("Bulk Error");
}
}
}
renderJSON(gson.toJson(indexNum));
}
private static Client getClient() {
// elasticsearch是启动的es服务名称
String cluster = Play.configuration.getProperty("cluster", "elasticsearch");
List<String> urls = Arrays.asList(Play.configuration.getProperty("urls", "localhost").split(","));
Settings settings = Settings.builder()
//es名称
.put("cluster.name", cluster)
// 是否自动嗅探整个集群的状态
.put("client.transport.sniff", true)
.build();
TransportClient client = new PreBuiltTransportClient(settings);
for(String url : urls) {
TransportAddress transportAddress = new InetSocketTransportAddress(new InetSocketAddress(url, 9300));
client.addTransportAddress(transportAddress);
}
return client;
}