搭建大型分布式服务(九)Springboot整合ES和RestHighlevelClient

·  阅读 744

一、本文要点

接上文,我们已经把SpringBoot整合mybatis和Hikari了,并且通过docker搭建好了ES和Kibana,本文将介绍SpringBoot如何整合ES,支持搜索功能。系列文章完整目录

  • junit 5 单元测试

  • restHighLevelClient 保存对象

  • restHighLevelClient 根据id获取对象

  • objectMapper序列化和反序列化

  • springboot整合elasticsearch

  • springboot + mybatis + druid + elasticsearch

二、开发环境

  • jdk 1.8
  • maven 3.6.2
  • mybatis 1.3.0
  • springboot 2.4.3
  • mysql 5.6.46
  • junit 5
  • es 6.8.4
  • idea 2020

三、修改pom.xml 增加依赖

        <!-- es -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.8.4</version>
        </dependency>
        <!-- Java High Level REST Client -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.8.4</version>
        </dependency>

复制代码

三、修改配置文件

修改application-dev.properties文件,同理,后面发布到测试、正式环境的话,修改对应的配置文件。

#################### ES ####################
elasticsearch.host=9.135.xxx.xxx
elasticsearch.port=9200
elasticsearch.type=member
elasticsearch.index=members
elasticsearch.username=xxx
elasticsearch.password=xxx
复制代码

五、增加配置类

1、增加ElasticSearchConfig.java,接收application-dev.peoperties的配置。

@Component("elasticSearchConfig")
@ConfigurationProperties(prefix = "elasticsearch")
@Data
public class ElasticSearchConfig {

    private String host;
    private int port;
    private String username;
    private String password;
    private String type;
    private String index;
}
复制代码

2、编写RestHighLevelClientConfiguration.java,配置restHighLevelClient。

@Configuration
public class RestHighLevelClientConfiguration {

    @Resource
    private ElasticSearchConfig elasticSearchConfig;

    @Bean("esObjectMapper")
    public ObjectMapper getEsObjectMapper() {
        return new ObjectMapper()
                .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                // .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
                .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
                .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    @Bean
    RestHighLevelClient restHighLevelClient() {

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(elasticSearchConfig.getUsername(), elasticSearchConfig.getPassword()));

        RestClientBuilder builder = RestClient
                .builder(new HttpHost(elasticSearchConfig.getHost(), elasticSearchConfig.getPort()))
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
                            // 超时时间
                            .setConnectTimeout(5 * 1000)
                            // 这就是Socket超时时间设置
                            .setSocketTimeout(5 * 1000);
                    httpClientBuilder
                            .setDefaultCredentialsProvider(credentialsProvider)
                            .setDefaultRequestConfig(requestConfigBuilder.build());
                    return httpClientBuilder;

                });

        return new RestHighLevelClient(builder);
    }
}
复制代码

3、修改MemberService.java.

@Slf4j
@Service
public class MemberService {

    @Resource
    private TblMemberInfoMapper tblMemberInfoMapper;

    @Resource
    private ElasticSearchConfig elasticSearchConfig;

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Resource(name = "esObjectMapper")
    private ObjectMapper objectMapper;

    public TblMemberInfo save(TblMemberInfo member) {

        tblMemberInfoMapper.insert(member);

        return member;
    }

    public void saveMemberIntoEs(String id, TblMemberInfo member) throws IOException {

        UpdateRequest req = new UpdateRequest(elasticSearchConfig.getIndex(),
                elasticSearchConfig.getType(), id);

        byte[] bytes;
        try {
            bytes = objectMapper.writeValueAsBytes(member);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
            return;
        }
        req.doc(bytes, XContentType.JSON).docAsUpsert(true).retryOnConflict(3)
                .timeout(TimeValue.timeValueMinutes(2))
                .detectNoop(true);

        restHighLevelClient.update(req, RequestOptions.DEFAULT);
    }

    public TblMemberInfo getMemberFromEsById(String id) throws IOException {

        GetRequest req = new GetRequest(elasticSearchConfig.getIndex(), elasticSearchConfig.getType(), id);
        GetResponse respone = restHighLevelClient.get(req, RequestOptions.DEFAULT);

        return objectMapper.readValue(respone.getSourceAsString(), TblMemberInfo.class);
    }
}
复制代码

六、运行一下

1、编写单元测试。

@Slf4j
@ActiveProfiles("dev")
@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional // 自动回滚单元测试插入DB的数据
public class MemberServiceTest {

    @Resource
    private MemberService memberService;

    @Resource(name = "esObjectMapper")
    private ObjectMapper objectMapper;
  
    @Test
    void getMemberFromEsById() throws IOException {

        TblMemberInfo member = new TblMemberInfo();
        member.setUid(1L);
        member.setUname("zhangsan");
        member.setUsex(1);
        member.setUbirth(new Date());
        member.setUtel("888");
        member.setUaddr("凌霄殿");
        member.setState(0);
        member.setDelFlag(0);
        member.setUphoto(null);

        memberService.saveMemberIntoEs(member.getUid() + "", member);

        TblMemberInfo ret = memberService.getMemberFromEsById(member.getUid() + "");
        log.info("--------------------------------------------------");
        log.info("result: {}", objectMapper.writeValueAsString(ret));

        assertThat(ret).isNotNull();
        assertThat(ret.getUname()).isEqualTo(member.getUname());
    }

}
复制代码

2、效果。

[2021-03-06 17:14:55.914] [main] [DEBUG] [org.elasticsearch.client.RestClient:?] - request [GET http://9.135.xxx.xxx:9200/members/member/1] returned [HTTP/1.1 200 OK]
[2021-03-06 17:14:55.945] [main] [INFO] [com.mmc.lesson.member.service.MemberServiceTest:?] - --------------------------------------------------
[2021-03-06 17:14:55.947] [main] [INFO] [com.mmc.lesson.member.service.MemberServiceTest:?] - result: {"uid":1,"uname":"zhangsan","usex":1,"ubirth":"2021-03-06 17:14:55","utel":"888","uaddr":"凌霄殿","state":0,"delFlag":0}
                                                                                            
复制代码

七、小结

这里只是简单介绍如何整合es,更加详细的用法请关注后续文章,完整代码地址:戳这里。下一篇《搭建大型分布式服务(十)Docker搭建开发环境安装Redis

加我一起交流学习!

分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改