ElasticSearch不采用注解实现所需功能
实体类 Vehicle
public class Vehicle {
private String id;
private String number;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
vehicle.json
{
"properties": {
"id": {
"type": "keyword"
},
"number": {
"type": "text"
}
}
}
工具类
/**
* 读取文件输出转为String类型
*/
public class Util {
private static final Logger Log = LoggerFactory.getLogger(Util.class);
public static String loadAsString(final String path){
try{
final File resource = new ClassPathResource(path).getFile();
return new String(Files.readAllBytes(resource.toPath()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
服务层
知识拓展
@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
@Service
public class IndexService {
private static final Logger LOG = LoggerFactory.getLogger(Util.class);
private static final List<String> INDICES_TO_CREATE = List.of(Indices.VEHICLE_INDEX);
private final RestHighLevelClient client;
@Autowired
public IndexService(@Qualifier("elasticsearchClient") RestHighLevelClient client) {
this.client = client;
}
@PostConstruct
public void tryToCreateIndices(){
final String settings = Util.loadAsString("static/es-settings.json");
for (final String indexName : INDICES_TO_CREATE){
try {
boolean indexExists = client
.indices()
.exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT);
if(indexExists){
continue;
}
final String mappings = Util.loadAsString("static/mapping/"+indexName+".json");
if(settings == null || mappings == null){
LOG.error("Filed to create index with name '{}'",indexName);
continue;
}
final CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.settings(settings, XContentType.JSON);
createIndexRequest.mapping(mappings,XContentType.JSON);
client.indices().create(createIndexRequest,RequestOptions.DEFAULT);
}catch (final Exception e){
LOG.error(e.getMessage(),e);
}
}
}
}
@Service
public class VehicleService {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final Logger LOG = LoggerFactory.getLogger(VehicleService.class);
private final RestHighLevelClient client;
@Autowired
public VehicleService(@Qualifier("elasticsearchClient") RestHighLevelClient client) {
this.client = client;
}
public Boolean index(final Vehicle vehicle){
try{
final String vehicleAsString = MAPPER.writeValueAsString(vehicle);
final IndexRequest request = new IndexRequest(Indices.VEHICLE_INDEX);
request.id(vehicle.getId());
request.source(vehicleAsString, XContentType.JSON);
//响应是否正常
final IndexResponse response = client.index(request, RequestOptions.DEFAULT);
return response!= null && response.status().equals(RestStatus.OK);
}catch (final Exception e){
LOG.error(e.getMessage(),e);
return false;
}
}
public Vehicle getById(final String vehicleId){
try{
final GetResponse documentFields = client.get(
new GetRequest(Indices.VEHICLE_INDEX,vehicleId),
RequestOptions.DEFAULT
);
if (documentFields == null || documentFields.isSourceEmpty()){
return null;
}
return MAPPER.readValue(documentFields.getSourceAsString(),Vehicle.class);
}catch (final Exception e) {
LOG.error(e.getMessage(),e);
return null;
}
}
}
@RestController
@RequestMapping("/api/vehicle")
public class VehicleController {
private final VehicleService service;
public VehicleController(VehicleService service) {
this.service = service;
}
@PostMapping
public void index(@RequestBody final Vehicle vehicle){
service.index(vehicle);
}
@GetMapping("/{id}")
public Vehicle getById(@PathVariable final String id){
return service.getById(id);
}
}
|