Skip to content

Commit acdd796

Browse files
Huang WenfengHuang Wenfeng
authored andcommitted
springboot集成elasticsearch demo
1 parent cac7ca3 commit acdd796

File tree

15 files changed

+896
-0
lines changed

15 files changed

+896
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
HELP.md
2+
/target/
3+
!.mvn/wrapper/maven-wrapper.jar
4+
5+
### STS ###
6+
.apt_generated
7+
.classpath
8+
.factorypath
9+
.project
10+
.settings
11+
.springBeans
12+
.sts4-cache
13+
14+
### IntelliJ IDEA ###
15+
.idea
16+
*.iws
17+
*.iml
18+
*.ipr
19+
20+
### NetBeans ###
21+
/nbproject/private/
22+
/nbbuild/
23+
/dist/
24+
/nbdist/
25+
/.nb-gradle/
26+
/build/
27+
28+
### VS Code ###
29+
.vscode/
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
## 基于SpringBoot整合ElasticSearch
2+
3+
4+
> 测试类记录了常用的操作API
5+
6+
- 官网文档地址:[Spring Data Elasticsearch](https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/)
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<parent>
6+
<groupId>org.springframework.boot</groupId>
7+
<artifactId>spring-boot-starter-parent</artifactId>
8+
<version>2.0.4.RELEASE</version>
9+
<relativePath/> <!-- lookup parent from repository -->
10+
</parent>
11+
<groupId>com.sxw</groupId>
12+
<artifactId>springboot-elasticsearch</artifactId>
13+
<version>0.0.1-SNAPSHOT</version>
14+
<name>springboot-elasticsearch</name>
15+
<description>Demo project for Spring Boot</description>
16+
17+
<properties>
18+
<java.version>1.8</java.version>
19+
</properties>
20+
21+
<dependencies>
22+
<dependency>
23+
<groupId>org.springframework.boot</groupId>
24+
<artifactId>spring-boot-starter-web</artifactId>
25+
</dependency>
26+
<!-- elasticsearch启动器 (必须)-->
27+
<dependency>
28+
<groupId>org.springframework.boot</groupId>
29+
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
30+
</dependency>
31+
32+
<dependency>
33+
<groupId>org.projectlombok</groupId>
34+
<artifactId>lombok</artifactId>
35+
<optional>true</optional>
36+
</dependency>
37+
<dependency>
38+
<groupId>org.springframework.boot</groupId>
39+
<artifactId>spring-boot-starter-test</artifactId>
40+
<scope>test</scope>
41+
</dependency>
42+
<dependency>
43+
<groupId>commons-beanutils</groupId>
44+
<artifactId>commons-beanutils</artifactId>
45+
<version>1.9.3</version>
46+
</dependency>
47+
<dependency>
48+
<groupId>org.springframework.boot</groupId>
49+
<artifactId>spring-boot-starter-aop</artifactId>
50+
</dependency>
51+
52+
<!-- 用于日志切面中,以 json 格式打印出入参 -->
53+
<dependency>
54+
<groupId>com.google.code.gson</groupId>
55+
<artifactId>gson</artifactId>
56+
<version>2.8.5</version>
57+
</dependency>
58+
</dependencies>
59+
60+
<build>
61+
<plugins>
62+
<plugin>
63+
<groupId>org.springframework.boot</groupId>
64+
<artifactId>spring-boot-maven-plugin</artifactId>
65+
</plugin>
66+
</plugins>
67+
</build>
68+
69+
</project>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.sxw.elasticsearch;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class SpringbootElasticsearchApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(SpringbootElasticsearchApplication.class, args);
11+
}
12+
13+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.sxw.elasticsearch.aspect;
2+
3+
import java.lang.annotation.*;
4+
5+
@Retention(RetentionPolicy.RUNTIME)
6+
@Target({ElementType.METHOD})
7+
@Documented
8+
public @interface WebLog {
9+
/**
10+
* 日志描述信息
11+
*
12+
* @return
13+
*/
14+
String description() default "";
15+
}
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
package com.sxw.elasticsearch.aspect;
2+
3+
import com.google.gson.Gson;
4+
import lombok.extern.slf4j.Slf4j;
5+
import org.aspectj.lang.JoinPoint;
6+
import org.aspectj.lang.ProceedingJoinPoint;
7+
import org.aspectj.lang.annotation.*;
8+
import org.springframework.context.annotation.Profile;
9+
import org.springframework.stereotype.Component;
10+
import org.springframework.web.context.request.RequestContextHolder;
11+
import org.springframework.web.context.request.ServletRequestAttributes;
12+
13+
import javax.servlet.http.HttpServletRequest;
14+
import java.lang.reflect.Method;
15+
16+
/**
17+
* 使用自定义注解,AOP 切面统一打印出入参日志
18+
* 参考链接:https://mp.weixin.qq.com/s/JThls6pYtWoQYjac_chSUQ
19+
*/
20+
@Aspect
21+
@Component
22+
@Profile({"dev", "test"})
23+
@Slf4j
24+
public class WebLogAspect {
25+
/** 换行符 */
26+
private static final String LINE_SEPARATOR = System.lineSeparator();
27+
28+
/** 以自定义 @WebLog 注解为切点 */
29+
@Pointcut("@annotation(com.sxw.elasticsearch.aspect.WebLog)")
30+
public void webLog() {}
31+
32+
/**
33+
* 在切点之前织入
34+
* @param joinPoint
35+
* @throws Throwable
36+
*/
37+
@Before("webLog()")
38+
public void doBefore(JoinPoint joinPoint) throws Throwable {
39+
// 开始打印请求日志
40+
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
41+
HttpServletRequest request = attributes.getRequest();
42+
43+
// 获取 @WebLog 注解的描述信息
44+
String methodDescription = getAspectLogDescription(joinPoint);
45+
46+
// 打印请求相关参数
47+
log.info("========================================== Start ==========================================");
48+
// 打印请求 url
49+
log.info("URL : {}", request.getRequestURL().toString());
50+
// 打印描述信息
51+
log.info("Description : {}", methodDescription);
52+
// 打印 Http method
53+
log.info("HTTP Method : {}", request.getMethod());
54+
// 打印调用 controller 的全路径以及执行方法
55+
log.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
56+
// 打印请求的 IP
57+
log.info("IP : {}", request.getRemoteAddr());
58+
// 打印请求入参
59+
log.info("Request Args : {}", new Gson().toJson(joinPoint.getArgs()));
60+
}
61+
62+
/**
63+
* 在切点之后织入
64+
* @throws Throwable
65+
*/
66+
@After("webLog()")
67+
public void doAfter() throws Throwable {
68+
// 接口结束后换行,方便分割查看
69+
log.info("=========================================== End ===========================================" + LINE_SEPARATOR);
70+
}
71+
72+
/**
73+
* 环绕 可以在切入点前后织入代码,并且可以自由的控制何时执行切点;
74+
* @param proceedingJoinPoint
75+
* @return
76+
* @throws Throwable
77+
*/
78+
@Around("webLog()")
79+
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
80+
long startTime = System.currentTimeMillis();
81+
Object result = proceedingJoinPoint.proceed();
82+
// 打印出参
83+
log.info("Response Args : {}", new Gson().toJson(result));
84+
// 执行耗时
85+
log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
86+
return result;
87+
}
88+
89+
90+
/**
91+
* 获取切面注解的描述
92+
*
93+
* @param joinPoint 切点
94+
* @return 描述信息
95+
* @throws Exception
96+
*/
97+
public String getAspectLogDescription(JoinPoint joinPoint)
98+
throws Exception {
99+
String targetName = joinPoint.getTarget().getClass().getName();
100+
String methodName = joinPoint.getSignature().getName();
101+
Object[] arguments = joinPoint.getArgs();
102+
Class targetClass = Class.forName(targetName);
103+
Method[] methods = targetClass.getMethods();
104+
StringBuilder description = new StringBuilder("");
105+
for (Method method : methods) {
106+
if (method.getName().equals(methodName)) {
107+
Class[] clazzs = method.getParameterTypes();
108+
if (clazzs.length == arguments.length) {
109+
description.append(method.getAnnotation(WebLog.class).description());
110+
break;
111+
}
112+
}
113+
}
114+
return description.toString();
115+
}
116+
117+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.sxw.elasticsearch.controller;
2+
3+
import com.sxw.elasticsearch.aspect.WebLog;
4+
import com.sxw.elasticsearch.model.User;
5+
import lombok.extern.slf4j.Slf4j;
6+
import org.springframework.web.bind.annotation.*;
7+
import org.springframework.web.multipart.MultipartFile;
8+
9+
/**
10+
* 使用自定义注解,AOP 切面统一打印出入参日志
11+
*/
12+
@RestController
13+
@Slf4j
14+
public class TestAopLogController {
15+
/**
16+
* POST 方式接口测试
17+
* @param user
18+
* @return
19+
*/
20+
@PostMapping("/user/login")
21+
@WebLog(description = "请求了用户登录接口")
22+
public User userLogin(@RequestBody User user) {
23+
log.info("user login ...");
24+
return user;
25+
}
26+
27+
/**
28+
* GET 方式接口测试
29+
* @return
30+
*/
31+
@GetMapping("/user/{id}")
32+
@WebLog(description = "请求了用户登录接口")
33+
public String findUserInfo(@PathVariable("id") String userId) {
34+
log.info("find user info ...");
35+
return "success";
36+
}
37+
38+
/**
39+
* GET 方式接口测试
40+
* @return
41+
*/
42+
@GetMapping("/test")
43+
public String test() {
44+
log.info("testGet ...");
45+
return "success";
46+
}
47+
48+
/**
49+
* 单文件上传接口测试
50+
* @return
51+
*/
52+
@PostMapping("/file/upload")
53+
public String testFileUpload(@RequestParam("file") MultipartFile file) {
54+
log.info("testFileUpload ...");
55+
return "success";
56+
}
57+
58+
/**
59+
* 多文件上传接口测试
60+
* @return
61+
*/
62+
@PostMapping("/multiFile/upload")
63+
public String testMultiFileUpload(@RequestParam("file") MultipartFile[] file) {
64+
log.info("testMultiFileUpload ...");
65+
return "success";
66+
}
67+
}

0 commit comments

Comments
 (0)