springboot+es(二)多数据源配置

43 篇文章 110 订阅
9 篇文章 1 订阅

上一篇文章简单写了 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();
    }
}
  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.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;
    }
}
好的,下面是代码: 1. 配置文件 ``` # datasource1 spring.datasource.ds1.url=jdbc:mysql://localhost:3306/db1?useSSL=false spring.datasource.ds1.username=root spring.datasource.ds1.password=123456 spring.datasource.ds1.driverClassName=com.mysql.cj.jdbc.Driver # datasource2 spring.datasource.ds2.url=jdbc:mysql://localhost:3306/db2?useSSL=false spring.datasource.ds2.username=root spring.datasource.ds2.password=123456 spring.datasource.ds2.driverClassName=com.mysql.cj.jdbc.Driver # Elasticsearch spring.elasticsearch.rest.uris=http://localhost:9200 spring.elasticsearch.rest.username=username spring.elasticsearch.rest.password=password spring.elasticsearch.rest.connection-timeout=10000 spring.elasticsearch.rest.read-timeout=10000 spring.data.elasticsearch.repositories.enabled=true spring.data.elasticsearch.cluster-name=elasticsearch spring.data.elasticsearch.cluster-nodes=localhost:9300 spring.data.elasticsearch.properties.request.headers.Authorization=Bearer your_auth_token # use Elasticsearch as the default data source spring.data.jpa.repository.support.JpaRepositoryFactoryBean.DEFAULT_ENTITY_MANAGER_FACTORY_REF=esEntityManagerFactory ``` 2. 实体类 ``` @Data @NoArgsConstructor @AllArgsConstructor @Builder @Entity @Table(indexes = { @Index(name = "idx_name", columnList = "name"), @Index(name = "idx_description", columnList = "description") }) public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String description; @Column(name="create_time") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") private LocalDateTime createTime; } ``` 注意,以上代码只是示例,具体代码需要根据实际情况进行调整。另外,要使用双数据源配置,还需要在代码中进行相关配置
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值