上一篇文章简单写了 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;
}
}