上一篇文章簡單寫了 springboot 和 es 的使用 點擊查看
這一篇說一下多數據源
多數據源配置
在config 文件夾下新增數據源配置,有幾個數據源就新增幾個配置類,例子是老師信息數據源 和學生信息數據源兩個 。
引入依賴
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.8.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.40</version>
</dependency>
1.配置文件添加多數據源配置
在application.properties 文件中增加數據源配置
elasticsearch.teacherInfo.userName=
elasticsearch.teacherInfo.password=
elasticsearch.teacherInfo.rest.hostNames=192.168.0.105
elasticsearch.teacherInfo.rest.port=9200
elasticsearch.studentInfo.userName=
elasticsearch.studentInfo.password=
elasticsearch.studentInfo.rest.hostNames=192.168.0.104
elasticsearch.studentInfo.rest.port=9200
2.配置數據源
1.新建老師信息數據源配置類
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TeacherInfoESRestClient {
public static final String NAME = "TeacherInfoESRestClient";
@Value("${elasticsearch.teacherInfo.userName}")
private String userName;
@Value("${elasticsearch.teacherInfo.password}")
private String password;
@Value("${elasticsearch.teacherInfo.rest.hostNames}")
private String hostName;
@Value("${elasticsearch.teacherInfo.rest.port}")
private Integer port;
@Bean(name = NAME, destroyMethod = "close")
public RestClient getRestClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostName, port));
//配置身份驗證
restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
return restClientBuilder.build();
}
}
- 新建學生數據源配置類
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StudentInfoESRestClient {
public static final String NAME = "StudentInfoESRestClient";
@Value("${elasticsearch.studentInfo.userName}")
private String userName;
@Value("${elasticsearch.studentInfo.password}")
private String password;
@Value("${elasticsearch.studentInfo.rest.hostNames}")
private String hostName;
@Value("${elasticsearch.studentInfo.rest.port}")
private Integer port;
@Bean(name = NAME, destroyMethod = "close")
public RestClient getRestClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostName, port));
//配置身份驗證
restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
return restClientBuilder.build();
}
}
3. 在service 中使用不同數據源操作
學生信息服務 StudentInfoServiceImpl
@Service
public class StudentInfoServiceImpl implements StudentInfoService {
private static final Logger logger = LoggerFactory.getLogger(StudentInfoServiceImpl.class);
private String INDEX = "student_info";
private String TYPE = "student";
private String SEARCH= "_search";
//此處引入 配置數據源 StudentInfoESRestClient
@Autowired
@Qualifier(StudentInfoESRestClient.NAME)
private RestClient restClient;
@Autowired
private EsService esService;
/**
* 根據學生id查詢
*
* @param mobile
* @param accountId
* @param docName
* @return
* @throws ServiceException
*/
@Override
public JSONObject detail(String id) {
JsonNode searchResponse;
String endpoint = "/" + INDEX + "/" +
TYPE + "/" + id;
searchResponse = esService.esSearch(null, endpoint, restClient);
if (null == searchResponse) {
return result;
}
JsonNode hitsNode = searchResponse.get("_source");
result = (JSONObject) JSONObject.parse(hitsNode.toString());
return result;
}
}
老師信息服務 TeacherInfoServiceImpl
@Service
public class TeacherInfoServiceImpl implements TeacherInfoService {
private static final Logger logger = LoggerFactory.getLogger(TeacherInfoServiceImpl.class);
private String INDEX = "teacher_info";
private String TYPE = "teacher";
private String SEARCH= "_search";
//此處引入 配置數據源 TeacherInfoESRestClient
@Autowired
@Qualifier(TeacherInfoESRestClient.NAME)
private RestClient restClient;
@Autowired
private EsService esService;
/**
* 根據手機號或者老師id查詢
*
* @param mobile
* @param accountId
* @param docName
* @return
* @throws ServiceException
*/
@Override
public JSONObject detail(String id, String mobile ) {
String endpoint = INDEX
+ TYPE
+ SEARCH;
JSONObject result = new JSONObject();
JsonNode searchResponse;
// 查詢語句
JSONObject search = searchDetailQuery(mobile, id);
searchResponse = esService.esSearch(search, endpoint, restClient);
if (null == searchResponse) {
return result;
}
//解析結果
JsonNode hitsNode = searchResponse.get("hits");
ArrayNode hitsArray = (ArrayNode) hitsNode.get("hits");
for (JsonNode hit : hitsArray) {
result = (JSONObject) JSONObject.parse(hit.get("_source").toString());
}
return result;
}
/**
* 根據手機號或者id 查詢 拼裝查詢語句
*
* @param mobile
* @param id
* @return
* @throws ServiceException
*/
private JSONObject searchDetailQuery(String mobile, String id) {
JSONObject term;
if (StringUtils.isNotEmpty(id)) {
// 用id 查詢
term = EsQueryUtils.getJSONObject("term", EsQueryUtils.getJSONObject("id", id));
} else {
//用手機號查詢
term = EsQueryUtils.getJSONObject("term", EsQueryUtils.getJSONObject("mobile", mobile));
}
JSONObject search = new JSONObject();
search.put("query", term);
return search;
}
}
es查詢服務類
package cn.miao.middle.account.service.inside;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* @author yyb
* @time 2020/2/18
*/
@Service
public class EsService {
protected static final ObjectMapper mapper = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(EsService.class);
/**
* ES查詢
*
* @param search
* @return
*/
public JsonNode esSearch(JSONObject search, String endpoint, RestClient restClient) {
JsonNode responseNode = null;
try {
logger.info("查詢es語句爲 {}, endpoint 爲:{}", search, endpoint.toString());
Request request = new Request(HttpGet.METHOD_NAME, endpoint);
if (search != null) {
String data = search.toString();
request.setJsonEntity(data);
}
try {
restClient.performRequest(request);
} catch (IOException e) {
logger.error("查詢es語句報錯爲 {}", e.getMessage());
}
Response response = restClient.performRequest(request);
String responseStr = EntityUtils.toString(response.getEntity());
logger.info("查詢結果爲", responseStr);
responseNode = mapper.readTree(responseStr);
} catch (IOException e) {
logger.error("查詢失敗", e);
}
return responseNode;
}
}