舒大少博客

一个95后少年的个人博客

当前时间为:
欢迎大家来到舒大少博客http://admin.evshou.com,广告合作以及淘宝商家推广请微信联系15357240395

2020java微服务架构之SpringBoot整合mybatis和ElasticSearch

2021-02-12 13:25:35
swq1822677238

手机扫码查看

2020java微服务架构之SpringBoot整合mybatis和ElasticSearch

SpringBoot整合mybatis和ElasticSearch

1.创建客户模块和搜索模块

2.准备客户模块的静态资源(页面,实体类,数据库)

3.准备搜索模块的资源(在ES中创建客户模块的索引)

3.1 导入ES的依赖

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.5.4</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.5.4</version>
</dependency>

3.2 编写连接ES的config配置类(搜索模块)

elasticsearch:
  port: 9200
  host: 192.168.2.123

3.2.1 然后创建config包

@Configuration
public class ElasticSearchConfig {
    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private Integer port;

    @Bean
    public RestHighLevelClient client(){
        RestClientBuilder clientBuilder= RestClient.builder(new HttpHost(host,port));

        // 创建 RestHighLevelClient
        return new RestHighLevelClient(clientBuilder);
    }
}

3.3 导入实体类并实现序列化接口(客户模块和搜索模块)

3.4 创建索引和测试数据

@SpringBootTest
class ElasticSearchTests{
    @Autowired
    private RestHighLevelClient client;

    String index="mvc-users";
    String type="users";

    @Test
    public void createIndex() throws Exception {
        //1. 准备索引的 settings
        Settings.Builder settings = Settings.builder().
                put("number_of_replicas", 1)
                .put("number_of_shards",3);
        //2. 准备索引的结构 mappings
        XContentBuilder mappings = JsonXContent.contentBuilder()
                .startObject()
                .startObject("properties")
                .startObject("username")
                .field("type", "text")
                .endObject()
                .startObject("identity")
                .field("type", "text")
                .endObject()
                .startObject("mobile")
                .field("type", "keyword")
                .endObject()
                .endObject()
                .endObject();
        // 3. 将 settings 和 mappings 封装到一个Request对象
        CreateIndexRequest request = new CreateIndexRequest(index)
                .settings(settings)
                .mapping(type,mappings);
        //4. 通过 client 对象去连接 ES 并执行创建索引
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        // 5. 输出
        System.out.println("response:"+response.toString());
    }
    @Test
    public void bulkCreateDoc() throws Exception {
        Users u1=new Users(1,"admin","admin","340801","男","133");
        Users u2=new Users(2,"admin2","admin2","340802","男","134");
        Users u3=new Users(3,"admin3","admin3","340803","女","135");
        Users u4=new Users(4,"admin4","admin4","340804","男","136");
        Users u5=new Users(5,"admin5","admin5","340805","女","137");

        ObjectMapper mapper = new ObjectMapper();

        String json1 = mapper.writeValueAsString(u1);
        String json2 = mapper.writeValueAsString(u2);
        String json3 = mapper.writeValueAsString(u3);
        String json4 = mapper.writeValueAsString(u4);
        String json5 = mapper.writeValueAsString(u5);

        //2. 创建Request,将准备好的数据封装进去
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest(index,type,u1.getId().toString()).source(json1, XContentType.JSON));
        request.add(new IndexRequest(index,type,u2.getId().toString()).source(json2,XContentType.JSON));
        request.add(new IndexRequest(index,type,u3.getId().toString()).source(json3,XContentType.JSON));
        request.add(new IndexRequest(index,type,u4.getId().toString()).source(json4,XContentType.JSON));
        request.add(new IndexRequest(index,type,u5.getId().toString()).source(json5,XContentType.JSON));

        //3. 用client执行
        BulkResponse resp = client.bulk(request, RequestOptions.DEFAULT);

        //4. 输出结果
        System.out.println(resp.toString());
    }
}

5.将客户模块进行 配置数据库连接信息和mybatis的配置

# tomcat 信息
server:
  port: 80
# 连接数据库信息
spring:
  datasource:
    url: jdbc:mysql:///springboot?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
# mybatis的配置
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.evshou.admin.demo.entity
  configuration:
    map-underscore-to-camel-case: true

5.1 在客户模块创建mapper包以及用户模块的mapper接口

5.2 在启动类添加@MapperScan(basePackages = “mapper包”)

5.3 在resources目录创建mapper目录以及映射文件xml,必须与接口名一致

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.evshou.admin.openapi.usermedel.mapper.UsersMapper">

</mapper>

6. 从ES中查询客户信息,并通过用户模块展示在页面中

6.1 在搜索模块创建service包并创建UsersService接口

String searchUsersByQuery(Map<String,Object> param) throws IOException;

6.2 创建impl包并且实现UsersService接口,然后添加注解 @Service

6.2.1 创建 vo包并且创建 LayUITableVO<T> 实体类

@Data
public class LayUITableVO<T> {
    private Integer code=0;
    private String msg="";
    private Long count;
    private List<T> data;
}

6.2.2 导入依赖

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
</dependency>

6.2.3 接口实现类

@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private RestHighLevelClient client;
    String index="openapi_user";
    String type="user";

    @Override
    public String searchUsersByQuery(Map<String, Object> param) throws IOException {
        // 1. SearchRequest
        SearchRequest request=new SearchRequest(index);
        request.types(type);
        // 2. 封装执行条件
        SearchSourceBuilder source=new SearchSourceBuilder();
        Object name = param.get("name");
        if(!StringUtils.isEmpty(name)){
            source.query(QueryBuilders.termQuery("username",name));
        }
        Object state = param.get("state");
        if (state != null) {
            source.query(QueryBuilders.termQuery("state",state));
        }
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        source.from((page-1)*limit);
        source.size(limit);
        request.source(source);
        // 3. 执行查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4. 封装数据
        LayUITableVO<Users> vo=new LayUITableVO<>();
        vo.setCount(response.getHits().getTotalHits());
        List<Users> data=new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            Users users=new Users();
            try {
                BeanUtils.populate(users,hit.getSourceAsMap());
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.add(users);
        }
        vo.setData(data);
        // 5. 返回数据
        return JSON.toJSON(vo);
    }
}

6.2.4 在接口方法右键 goto test

@SpringBootTest
class UsersServiceTest {
    @Autowired
    private UsersService usersService;

    @Test
    void searchUsersByQuery() throws IOException {
        Map<String,Object> param=new HashMap<>();
        param.put("page",1);
        param.put("limit",10);
        String s = usersService.searchUsersByQuery(param);
        System.out.println(s);
    }
}

6.2.5 创建controller包并且创建UsersController

@RestController
@RequestMapping("/search/users")
public class UsersController {
    @Autowired
    private UsersService service;

    @PostMapping(value = "/table",produces = "application/json;charset=utf-8")
    public String table(@RequestBody Map<String,Object> param) throws Exception{
        // 调用 service 查询数据, 直接返回
        return service.searchUsersByQuery(param);
    }
}

6.3 客户模块

6.3.1 创建service包以及接口

public interface UsersService {
    String findUsersByQuery(Map<String,Object> parameter);
}

6.3.2 创建service.impl包以及接口实现类

@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public String findUsersByQuery(Map<String, Object> parameter) {
        // 1.准备头信息和请求参数
        String json = JSON.toJSON(parameter);
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<String> entity=new HttpEntity<>(json,httpHeaders);
        // 2. 使用 RestTemplate 调用搜索模块
        return restTemplate.postForObject("http://localhost:8080/search/users/table", entity, String.class);
    }
}

6.3.3 创建config包并且创建 RestTemplateConfig 类

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

6.3.4 将搜索模块的utils复制到客户模块中

6.3.5 在接口右键 goto test

@SpringBootTest
class UsersServiceTest {
    @Autowired
    private UsersService service;

    @Test
    void findUsersByQuery() {
        Map<String,Object> parameter=new HashMap<>();
        parameter.put("page",1);
        parameter.put("limit",10);
        parameter.put("name","admin");
        String result = service.findUsersByQuery(parameter);
        System.out.println(result);
    }
}

6.4 在 客户模块 创建 controller包并且创建UsersController 类

@RestController
@RequestMapping("/search/users")
public class UsersController {
    @Autowired
    private UsersService service;
    @GetMapping(value = "/table",produces = "application/json;charset=utf-8")
    public String table(@RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer limit,
                        String name,Integer state){
        // 1. 封装参数
        Map<String,Object> parameter=new HashMap<>();
        parameter.put("page",page);
        parameter.put("limit",limit);
        parameter.put("name",name);
        parameter.put("state",state);
        // 2. 调用 service 查询数据,然后返回数据
        return service.findUsersByQuery(parameter);
    }
}

6.5 搜索模块进行添加用户信息

6.5.1 在搜索模块的service接口添加 添加用户方法

void addUsers(Users users) throws IOException;

6.5.2 在搜索模块的service实现类

在类的上方添加注解 @Slf4j

@Override
public void addUsers(Users users) throws IOException {
    // 1. 创建 indexRequest
    IndexRequest request=new IndexRequest(index,type,users.getId()+"");
    // 2. 封装数据
    request.source(JSON.toJSON(users), XContentType.JSON);
    // 3. 执行添加
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    // 4. 判断添加是否成功(失败,抛出异常)
    if(!"CREATED".equalsIgnoreCase(response.getResult().toString())){
        log.error("[向ES添加用户信息失败] index={},type={},users={}",index,type,users);
        throw new RuntimeException("[向ES添加用户信息失败]");
    }
}

6.5.3 在测试类添加方法

@Test
void addUsers() throws IOException {
    Users users=new Users(6,"admin6","admin6","166","166","62220166",996.6,1);
    service.addUsers(users);
}

6.5.4 在搜索模块的controller类添加

@PostMapping(value = "/add")
public void add(@RequestBody Users users) throws IOException {
    service.addUsers(users);
}

6.6 用户模块模块进行添加用户信息

6.6.1 用户模块service接口

void add(Users users);

6.6.2 用户模块service实现类

@Service
@Slf4j
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper mapper;
    @Override
    @Transactional
    public void add(Users users) {
        // 1. 调用 mapper 添加数据到 mysql
        Integer add = mapper.add(users);
        // 2. 判断添加是否成功
        if(add!=1){
            log.error("[添加用户信息失败] users={}",users);
            throw new RuntimeException("[添加用户信息失败]");
        }
        // 3. 调用搜索模块,添加数据到 ES
        // 1.准备头信息和请求参数
        String json = JSON.toJSON(users);
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<String> entity=new HttpEntity<>(json,httpHeaders);
        // 2. 使用 RestTemplate 调用搜索模块
        restTemplate.postForObject("http://localhost:8080/search/users/add", entity, String.class);
    }
}

6.6.3 用户模块mapper

Integer add(Users users);

6.6.4 用户模块mapper映射

<insert id="add" parameterType="Users" useGeneratedKeys="true" keyProperty="id">
    insert into users values(null,#{username},#{password},#{mobile},#{identity},#{account},#{money},#{state})
</insert>

6.6.5 用户模块mapper测试类

@SpringBootTest
class UsersMapperTest {
    @Autowired
    private UsersMapper mapper;

    @Test
    void add() {
        Users users=new Users(null,"admin12","admin12","1712","1712","62221712",121212.12,1);
        Integer add = mapper.add(users);
        System.out.println(add+"\t"+users);
    }
}

6.6.6 用户模块的service测试

@Test
void add(){
    Users users=new Users(null,"admin16","admin16","1716","1716","62221716",16.16,1);
    service.add(users);
}

6.7 用户模块的controller

6.7.1 创建 vo 包并且创建 ResultVO 类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResultVO {
    private Boolean status;
    private String message;
    private Object result;
    public ResultVO(Boolean status, String message) {
        this.status = status;
        this.message = message;
    }
}

6.7.2 controller

@PostMapping("/add")
public ResultVO add(Users users){
    try {
        // 1. 调用 service 执行添加
        service.add(users);
        // 2. 返回json
        return new ResultVO(true,"添加成功");
    } catch (RuntimeException e) {
        e.printStackTrace();
        return new ResultVO(false,e.getMessage());
    }
}

 

发表评论

邮箱地址不会被公开。 必填项已用*标注