자바 연결 ElasticSearch 클 러 스 터

2708 단어
/*
 *es   
 *
 */

@Configuration
public class ElasticSearchDataSourceConfigurer {

    private static final Logger LOG = LogManager.getLogger(ElasticSearchDataSourceConfigurer.class);


    @Bean
    public TransportClient getESClient() {
        //      
        Settings settings = Settings.builder().put("cluster.name", "bigData-cluster").put("client.transport.sniff", true).build();
        //  client
        TransportClient client = null;
        try {
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(""), 9300));//  ip
            LOG.info("ESClient      ");
        } catch (UnknownHostException e) {
            LOG.info("ESClient      ");
            e.printStackTrace();
        }
        return client;
    }


}
/**
 * Simple to Introduction
 *
 * @Description: [   ]
 */
@Repository
public class UserDaoImpl implements userDao {

	private static final String INDEXNAME = "user";//  
	private static final String TYPENAME = "info";

	@Resource
	TransportClient transportClient;

	@Override
	public int addUser(User[] user) {
		IndexResponse indexResponse = null;
		int successNum = 0;
		for (int i = 0; i < user.length; i++) {
			UUID uuid = UUID.randomUUID();
			String str = uuid.toString();
			String jsonValue = null;
			try {
				jsonValue = JsonUtil.object2JsonString(user[i]);
				if (jsonValue != null) {
					indexResponse = transportClient.prepareIndex(INDEXNAME, TYPENAME, str).setSource(jsonValue)
							.execute().actionGet();
					successNum++;
				}
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}

		}
		return successNum;
	}

}

/**
 *    
 */
public static void bathAddUser(TransportClient client, List<User> users) {

		BulkRequestBuilder bulkRequest = transportClient.prepareBulk();
		for (int i = 0; i < users.size(); i++) {
			UUID uuid = UUID.randomUUID();
			String str = uuid.toString();

			String jsonValue = null;
			try {
				jsonValue = JsonUtil.object2JsonString(users.get(i));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			bulkRequest.add(client.prepareIndex("user", "info", str).setSource(jsonValue));
			//        
			if (i % 10000 == 0) {
				bulkRequest.execute().actionGet();
			}
			System.out.println("     " + i + "   ");
		}

	}


좋은 웹페이지 즐겨찾기