# springboot_test **Repository Path**: stefanpy/springboot_test ## Basic Information - **Project Name**: springboot_test - **Description**: 一些功能测试 - **Primary Language**: Java - **License**: Not specified - **Default Branch**: dev - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2018-04-26 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 测试目录 ### 1. springboot参数绑定测试 ``` @ConfigurationProperties(prefix = "userconfig") 这个注解在springboot2.x里会报找不到该注解的异常,但不影响操作。 ``` 绑定参数还可以通过@Value("${}"),把一个参数绑定 ``` @Value("${service.hello}") ``` @Value()目前测试在普通类和service、controller中都可以使用。 注:@Value()经常和@Component配套使用 ### 2. elasticsearch使用测试(配置、CRUD) #### es配置 导入依赖: ``` org.elasticsearch.client transport ``` 建立配置类: ``` import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.net.InetAddress; import java.net.UnknownHostException; /** * Create by stefan * Date on 2018-04-25 21:21 * Convertion over Configuration! */ @Configuration public class EsConfig { @Bean public TransportClient client() throws UnknownHostException { //建立es node InetSocketTransportAddress node = new InetSocketTransportAddress( InetAddress.getByName("localhost"), 9300 ); //建立es配置信息settings Settings settings = Settings.builder() .put("cluster.name","stefan") .build(); //绑定settings,并添加node TransportClient client = new PreBuiltTransportClient(settings); client.addTransportAddress(node); return client; } } //es的默认端口号是9200,但是在springboot里es的端口号是9300。 ``` #### es的CRUD es的接口遵循restful风格 ``` import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.search.SearchHit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * Create by stefan * Date on 2018-04-25 21:30 * Convertion over Configuration! */ @RestController @Slf4j public class Appication { @Autowired private TransportClient client; //简单查询 @GetMapping("/get/book/novel") public ResponseEntity get(@RequestParam String id){ log.info("{}",client.connectedNodes()); GetResponse result = client.prepareGet("book","novel",id).get(); if(!result.isExists()){ return new ResponseEntity(HttpStatus.NOT_FOUND); } return new ResponseEntity(result.getSource(), HttpStatus.OK); } // 新增 @PostMapping("/add/book/novel") public ResponseEntity add(@RequestParam String author, @RequestParam String title, @RequestParam(name = "word_count") int wordCount, @RequestParam(name = "publish_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date publishDate){ try { XContentBuilder content = XContentFactory.jsonBuilder().startObject() .field("author",author) .field("title",title) .field("word_count",wordCount) .field("publish_date",publishDate.getTime()) .endObject(); IndexResponse result = client.prepareIndex("book","novel") .setSource(content) .get(); return new ResponseEntity(result.getId(),HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } // 删除数据 @DeleteMapping("delete/book/novel") public ResponseEntity delete(@RequestParam String id){ DeleteResponse result = client.prepareDelete("book","novel",id).get(); return new ResponseEntity(result.getResult().toString(),HttpStatus.OK); } // 更新数据 @PutMapping("update/book/novel") public ResponseEntity update(@RequestParam String id,@RequestParam(required = false) String author,@RequestParam(required = false) String title){ UpdateRequest updateRequest = new UpdateRequest("book","novel",id); try { XContentBuilder builder = XContentFactory.jsonBuilder().startObject(); if (title != null){ builder.field("title",title); } if (author != null){ builder.field("author",author); builder.endObject(); updateRequest.doc(builder); } } catch (IOException e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } try { UpdateResponse result = client.update(updateRequest).get(); return new ResponseEntity(result.getResult().toString(),HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } // 复合查询 @PostMapping("query/book/novel") public ResponseEntity query(@RequestParam(required = false) String author, @RequestParam(required = false) String title, @RequestParam(name = "gt_word_count",defaultValue = "0") int gtWordCount, @RequestParam(name = "lt_word_count",required = false) Integer ltWordCount ){ BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); if (author != null){ //boolQueryBuilder.must(QueryBuilders.matchQuery("author",author)); boolQueryBuilder.should(QueryBuilders.matchQuery("author",author)); } if (title != null){ //boolQueryBuilder.must(QueryBuilders.matchQuery("title",title)); boolQueryBuilder.should(QueryBuilders.matchQuery("title",title)); } RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("word_count") .from(gtWordCount); if (ltWordCount != null && ltWordCount >0){ rangeQueryBuilder.to(ltWordCount); } boolQueryBuilder.filter(rangeQueryBuilder); SearchRequestBuilder builder = client.prepareSearch("book") .setTypes("novel") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(boolQueryBuilder); log.info("查询数据{}",builder); SearchResponse response = builder.get(); List> result = new ArrayList<>(); for (SearchHit hit:response.getHits()){ result.add(hit.getSource()); } return new ResponseEntity(result,HttpStatus.OK); } } ```