Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Sign in
Toggle navigation
U
unififi-spring-cloud-guide
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
lihaipeng
unififi-spring-cloud-guide
Commits
d1f61698
Commit
d1f61698
authored
Nov 10, 2020
by
lihaipeng
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
modify
parent
d92e6fae
Changes
34
Expand all
Hide whitespace changes
Inline
Side-by-side
Showing
34 changed files
with
1090 additions
and
645 deletions
+1090
-645
pom.xml
pom.xml
+0
-1
pom.xml
unififi-demo-api/pom.xml
+5
-0
User.java
unififi-demo-api/src/main/java/com/unififi/model/User.java
+2
-0
pom.xml
unififi-demo1-service/pom.xml
+4
-5
MybatisPlusConfig.java
...in/java/com/unififi/config/mybatis/MybatisPlusConfig.java
+0
-3
SwaggerConfig.java
...c/main/java/com/unififi/config/swagger/SwaggerConfig.java
+2
-3
Demo1Controller.java
...src/main/java/com/unififi/controller/Demo1Controller.java
+1
-0
bootstrap.yml
unififi-demo1-service/src/main/resources/bootstrap.yml
+7
-12
logback-spring.xml
unififi-demo1-service/src/main/resources/logback-spring.xml
+11
-3
ControllerExceptionHandler.java
...n/java/com/unififi/config/ControllerExceptionHandler.java
+0
-49
ControllerLogAdvice.java
...src/main/java/com/unififi/config/ControllerLogAdvice.java
+0
-109
ControllerLogAdviceConfig.java
...in/java/com/unififi/config/ControllerLogAdviceConfig.java
+0
-28
HttpMessageConverterConfig.java
...n/java/com/unififi/config/HttpMessageConverterConfig.java
+0
-79
RestTemplateConfig.java
.../src/main/java/com/unififi/config/RestTemplateConfig.java
+0
-40
ServiceExceptionAspect.java
.../main/java/com/unififi/config/ServiceExceptionAspect.java
+0
-35
SwaggerConfig.java
...rvice/src/main/java/com/unififi/config/SwaggerConfig.java
+1
-1
UnififiProperties.java
...e/src/main/java/com/unififi/config/UnififiProperties.java
+0
-127
UnififiRestTemplateLogInterceptor.java
...com/unififi/config/UnififiRestTemplateLogInterceptor.java
+0
-66
Demo2Controller.java
...src/main/java/com/unififi/controller/Demo2Controller.java
+9
-7
UserServiceImpl.java
...c/main/java/com/unififi/service/impl/UserServiceImpl.java
+2
-4
bootstrap.yml
unififi-demo2-service/src/main/resources/bootstrap.yml
+4
-1
logback-spring.xml
unififi-demo2-service/src/main/resources/logback-spring.xml
+2
-2
pom.xml
unififi-gateway/pom.xml
+258
-25
NacosDataSourceProperties.java
...sentinel/datasource/config/NacosDataSourceProperties.java
+142
-0
NacosDataSourceFactoryBean.java
...el/datasource/factorybean/NacosDataSourceFactoryBean.java
+164
-0
GatewayApplication.java
...gateway/src/main/java/com/unififi/GatewayApplication.java
+44
-0
GatewayConfiguration.java
...rc/main/java/com/unififi/config/GatewayConfiguration.java
+121
-0
UnififiGatewayProperties.java
...ain/java/com/unififi/config/UnififiGatewayProperties.java
+35
-0
Constants.java
...gateway/src/main/java/com/unififi/constant/Constants.java
+17
-0
AuthenticationFilter.java
...rc/main/java/com/unififi/filter/AuthenticationFilter.java
+134
-0
GatewayApplication.java
...src/main/java/com/unififi/gateway/GatewayApplication.java
+0
-18
AuthenticationFilter.java
...java/com/unififi/gateway/filter/AuthenticationFilter.java
+0
-25
application.yml_bak
unififi-gateway/src/main/resources/application.yml_bak
+1
-1
bootstrap.yml
unififi-gateway/src/main/resources/bootstrap.yml
+124
-1
No files found.
pom.xml
View file @
d1f61698
...
...
@@ -16,7 +16,6 @@
<name>
unififi-spring-cloud-guide
</name>
<packaging>
pom
</packaging>
<modules>
<module>
unififi-demo-api
</module>
<module>
unififi-demo1-service
</module>
...
...
unififi-demo-api/pom.xml
View file @
d1f61698
...
...
@@ -20,6 +20,11 @@
<artifactId>
validation-api
</artifactId>
<version>
2.0.1.Final
</version>
</dependency>
<dependency>
<groupId>
com.unififi
</groupId>
<artifactId>
unififi-core
</artifactId>
<version>
2.0.0
</version>
</dependency>
<dependency>
<groupId>
org.springframework.cloud
</groupId>
<artifactId>
spring-cloud-openfeign-core
</artifactId>
...
...
unififi-demo-api/src/main/java/com/unififi/model/User.java
View file @
d1f61698
package
com
.
unififi
.
model
;
import
com.fesf.annotation.EnableTimeZone
;
import
io.swagger.annotations.ApiModel
;
import
io.swagger.annotations.ApiModelProperty
;
import
lombok.Data
;
...
...
@@ -18,5 +19,6 @@ public class User {
@ApiModelProperty
(
value
=
"年龄"
)
private
Integer
age
;
@EnableTimeZone
private
Date
birthday
;
}
unififi-demo1-service/pom.xml
View file @
d1f61698
...
...
@@ -27,11 +27,6 @@
<artifactId>
u2c-scheduler-dto
</artifactId>
<version>
2.0.0
</version>
</dependency>
<dependency>
<groupId>
com.unififi
</groupId>
<artifactId>
unififi-core
</artifactId>
<version>
2.0.0
</version>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-actuator
</artifactId>
...
...
@@ -126,6 +121,10 @@
<artifactId>
dynamic-config-spring-boot-starter
</artifactId>
<version>
0.1.0.RELEASE
</version>
</dependency>
<dependency>
<groupId>
org.springframework.cloud
</groupId>
<artifactId>
spring-cloud-starter-sleuth
</artifactId>
</dependency>
<!-- 测试相关 -->
<dependency>
<groupId>
org.springframework.boot
</groupId>
...
...
unififi-demo1-service/src/main/java/com/unififi/config/mybatis/MybatisPlusConfig.java
View file @
d1f61698
...
...
@@ -20,11 +20,8 @@ public class MybatisPlusConfig {
@Bean
public
PaginationInterceptor
paginationInterceptor
()
{
PaginationInterceptor
paginationInterceptor
=
new
PaginationInterceptor
();
paginationInterceptor
.
setOverflow
(
false
);
paginationInterceptor
.
setLimit
(
10
);
paginationInterceptor
.
setCountSqlParser
(
new
JsqlParserCountOptimize
(
true
));
List
<
ISqlParser
>
sqlParserList
=
new
ArrayList
<>();
// 攻击 SQL 阻断解析器、加入解析链
sqlParserList
.
add
(
new
BlockAttackSqlParser
());
paginationInterceptor
.
setSqlParserList
(
sqlParserList
);
return
paginationInterceptor
;
...
...
unififi-demo1-service/src/main/java/com/unififi/config/swagger/SwaggerConfig.java
View file @
d1f61698
package
com
.
unififi
.
config
.
swagger
;
import
io.swagger.annotations.ApiOperation
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
...
...
@@ -26,8 +27,6 @@ public class SwaggerConfig {
@Value
(
"${spring.application.name}"
)
private
String
serviceName
;
private
static
final
String
basePackage
=
"com.unififi.controller"
;
@Bean
public
Docket
docket
()
{
return
new
Docket
(
DocumentationType
.
SWAGGER_2
)
...
...
@@ -36,7 +35,7 @@ public class SwaggerConfig {
.
genericModelSubstitutes
(
Response
.
class
)
.
forCodeGeneration
(
true
)
.
select
()
.
apis
(
RequestHandlerSelectors
.
basePackage
(
basePackage
))
.
apis
(
RequestHandlerSelectors
.
withMethodAnnotation
(
ApiOperation
.
class
))
.
paths
(
PathSelectors
.
any
())
.
build
();
}
...
...
unififi-demo1-service/src/main/java/com/unififi/controller/Demo1Controller.java
View file @
d1f61698
...
...
@@ -75,6 +75,7 @@ public class Demo1Controller {
log
.
info
(
"header. token:{}"
,
request
.
getHeader
(
"Authorization"
));
User
user
=
null
;
user
=
userApi
.
get
(
name
,
age
);
log
.
info
(
"user.birthdy:{}"
,
user
.
getBirthday
());
// try {
// } catch (Exception e) {
// log.error("Exception:", e);
...
...
unififi-demo1-service/src/main/resources/bootstrap.yml
View file @
d1f61698
...
...
@@ -4,10 +4,6 @@ server:
enabled
:
true
min-response-size
:
2048
mime-types
:
'
application/json'
endpoints
:
web
:
exposure
:
include
:
'
*'
shutdown
:
graceful
spring
:
redis
:
...
...
@@ -67,14 +63,13 @@ spring:
unififi.version
:
'
@unififi-service.version@'
user.home
:
${user.home}
# 测试时使用配置服务列表
#unififi-demo2-service:
# ribbon:
# NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
# listOfServers: 39.106.6.97:18080
unififi-demo2-service
:
ribbon
:
NFLoadBalancerRuleClassName
:
com.unififi.loadbalancer.UnififiRule
#NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
#listOfServers: 39.106.6.97:18080
unififi
:
#controller-pointcut: 'execution(* com.*.controller.*.*(..))'
loadbalancer
:
rule
:
RandomWeight
swagger
:
enable
:
true
unififi-demo1-service/src/main/resources/logback-spring.xml
View file @
d1f61698
<?xml version="1.0" encoding="UTF-8"?>
<configuration
scan=
"true"
scanPeriod=
"60 seconds"
debug=
"false"
>
<springProperty
scope=
"context"
name=
"logPath"
source=
"unififi.logs.path"
defaultValue=
"${user.home}/logs"
/>
<springProperty
scope=
"context"
name=
"appName"
source=
"spring.application.name"
/>
<springProperty
scope=
"context"
name=
"ip"
source=
"spring.cloud.client.ip-address"
/>
<property
name=
"LOG_HOME"
value=
"${logPath}"
/>
<property
name=
"APP_NAME"
value=
"unififi-demo1-service"
/>
<property
name=
"APP_NAME"
value=
"${appName}"
/>
<property
name=
"CONSOLE_LOG_PATTERN"
value=
"%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level ${appName} ${ip} %X{unififi-requestId} %X{X-B3-TraceId} %X{X-B3-SpanId} %X{X-B3-ParentSpanId} - %msg%n"
/>
<!-- 控制台输出 -->
<appender
name=
"STDOUT"
class=
"ch.qos.logback.core.ConsoleAppender"
>
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level %logger - %msg%n
</pattern>
<!-- <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level %logger - %msg%n</pattern>-->
<pattern>
${CONSOLE_LOG_PATTERN}
</pattern>
</encoder>
</appender>
...
...
@@ -21,7 +28,8 @@
</rollingPolicy>
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level - %msg%n
</pattern>
<!-- <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level - %msg%n</pattern>-->
<pattern>
${CONSOLE_LOG_PATTERN}
</pattern>
</encoder>
</appender>
...
...
unififi-demo2-service/src/main/java/com/unififi/config/ControllerExceptionHandler.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
config
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.web.HttpRequestMethodNotSupportedException
;
import
org.springframework.web.bind.MethodArgumentNotValidException
;
import
org.springframework.web.bind.annotation.ExceptionHandler
;
import
org.springframework.web.bind.annotation.ResponseBody
;
import
org.springframework.web.bind.annotation.RestControllerAdvice
;
import
java.util.HashMap
;
import
java.util.Map
;
/**
* 统一异常处理
*/
@Slf4j
@RestControllerAdvice
public
class
ControllerExceptionHandler
{
@ResponseBody
@ExceptionHandler
(
Exception
.
class
)
public
Map
handleException
(
Exception
e
)
{
Map
map
=
new
HashMap
();
map
.
put
(
"code"
,
500
);
map
.
put
(
"msg"
,
e
.
getMessage
());
log
.
error
(
"Exception: "
,
e
);
return
map
;
}
@ResponseBody
@ExceptionHandler
(
HttpRequestMethodNotSupportedException
.
class
)
public
Map
handleHttpRequestMethodNotSupportedException
(
HttpRequestMethodNotSupportedException
e
)
{
Map
map
=
new
HashMap
();
map
.
put
(
"code"
,
501
);
map
.
put
(
"msg"
,
e
.
getMessage
());
log
.
error
(
"HttpRequestMethodNotSupportedException: "
,
e
);
return
map
;
}
@ResponseBody
@ExceptionHandler
(
MethodArgumentNotValidException
.
class
)
public
Map
handleMethodArgumentNotValidException
(
MethodArgumentNotValidException
e
)
{
Map
map
=
new
HashMap
();
MethodArgumentNotValidException
exception
=
(
MethodArgumentNotValidException
)
e
;
map
.
put
(
"code"
,
502
);
map
.
put
(
"msg"
,
exception
.
getBindingResult
().
getAllErrors
().
get
(
0
).
getDefaultMessage
());
log
.
error
(
"MethodArgumentNotValidException: "
,
e
);
return
map
;
}
}
unififi-demo2-service/src/main/java/com/unififi/config/ControllerLogAdvice.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
config
;
import
com.alibaba.fastjson.JSON
;
import
com.alibaba.fastjson.JSONArray
;
import
org.aopalliance.intercept.MethodInterceptor
;
import
org.aopalliance.intercept.MethodInvocation
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.web.context.request.RequestAttributes
;
import
org.springframework.web.context.request.RequestContextHolder
;
import
org.springframework.web.context.request.ServletRequestAttributes
;
import
javax.servlet.http.HttpServletRequest
;
import
java.lang.reflect.Method
;
import
java.util.concurrent.TimeUnit
;
public
class
ControllerLogAdvice
implements
MethodInterceptor
{
private
final
static
Logger
logger
=
LoggerFactory
.
getLogger
(
"ControllerLog"
);
private
UnififiProperties
unififiProperties
;
public
ControllerLogAdvice
(
UnififiProperties
unififiProperties
)
{
this
.
unififiProperties
=
unififiProperties
;
}
@Override
public
Object
invoke
(
MethodInvocation
invocation
)
throws
Throwable
{
String
sortMethodName
=
getSortMethodName
(
invocation
.
getMethod
());
try
{
long
start
=
System
.
nanoTime
();
RequestAttributes
ra
=
RequestContextHolder
.
getRequestAttributes
();
HttpServletRequest
request
=
((
ServletRequestAttributes
)
ra
).
getRequest
();
String
requestData
=
null
;
if
(
"POST"
.
equalsIgnoreCase
(
request
.
getMethod
())
||
"PUT"
.
equalsIgnoreCase
(
request
.
getMethod
()))
{
requestData
=
JSONArray
.
toJSONString
(
invocation
.
getArguments
());
}
else
if
(
"GET"
.
equalsIgnoreCase
(
request
.
getMethod
()))
{
requestData
=
request
.
getQueryString
();
}
if
(
logger
.
isInfoEnabled
()
&&
unififiProperties
.
getLogger
().
getController
().
isEnabled
())
{
if
(!
unififiProperties
.
getLogger
().
getController
().
getSkipMethodSigns
().
contains
(
sortMethodName
))
{
logger
.
info
(
"UNIFIFI-REQ-[{}] {}"
,
sortMethodName
,
(
requestData
!=
null
?
requestData
:
""
));
}
}
Object
result
=
invocation
.
proceed
();
long
elapsedTime
=
TimeUnit
.
NANOSECONDS
.
toMillis
(
System
.
nanoTime
()
-
start
);
String
responseData
=
null
;
if
(
result
!=
null
)
{
responseData
=
JSON
.
toJSONString
(
result
);
}
if
(
logger
.
isInfoEnabled
()
&&
unififiProperties
.
getLogger
().
getController
().
isEnabled
())
{
if
(!
unififiProperties
.
getLogger
().
getController
().
getSkipMethodSigns
().
contains
(
sortMethodName
))
{
if
(
unififiProperties
.
getLogger
().
getController
().
getIgnoreResponseDataMethodSigns
().
contains
(
sortMethodName
))
{
logger
.
info
(
"UNIFIFI-RESP-[{}] IGNORE_DATA size:{} spend:{}ms"
,
sortMethodName
,
(
responseData
!=
null
?
responseData
.
length
()
:
0
),
elapsedTime
);
}
else
{
logger
.
info
(
"UNIFIFI-RESP-[{}] {} size:{} spend:{}ms"
,
sortMethodName
,
(
responseData
!=
null
?
responseData
:
""
),
(
responseData
!=
null
?
responseData
.
length
()
:
0
),
elapsedTime
);
}
}
}
return
result
;
}
catch
(
Throwable
throwable
)
{
if
(
logger
.
isErrorEnabled
()
&&
unififiProperties
.
getLogger
().
getController
().
isEnabled
())
{
logger
.
error
(
"UNIFIFI-RESP-[{}] [{}]{}"
,
sortMethodName
,
throwable
.
getClass
().
getSimpleName
(),
throwable
.
getMessage
());
}
return
throwable
;
}
}
private
String
getSortMethodName
(
Method
method
)
{
StringBuilder
sb
=
new
StringBuilder
();
appendType
(
sb
,
method
.
getDeclaringClass
(),
false
);
sb
.
append
(
"."
);
sb
.
append
(
method
.
getName
());
sb
.
append
(
"("
);
Class
<?>[]
parametersTypes
=
method
.
getParameterTypes
();
appendTypes
(
sb
,
parametersTypes
,
false
,
false
);
sb
.
append
(
")"
);
return
sb
.
toString
();
}
private
void
appendTypes
(
StringBuilder
sb
,
Class
<?>[]
types
,
boolean
includeArgs
,
boolean
useLongReturnAndArgumentTypeName
)
{
if
(
includeArgs
)
{
for
(
int
size
=
types
.
length
,
i
=
0
;
i
<
size
;
i
++)
{
appendType
(
sb
,
types
[
i
],
useLongReturnAndArgumentTypeName
);
if
(
i
<
size
-
1
)
{
sb
.
append
(
","
);
}
}
}
else
{
if
(
types
.
length
!=
0
)
{
sb
.
append
(
".."
);
}
}
}
private
void
appendType
(
StringBuilder
sb
,
Class
<?>
type
,
boolean
useLongTypeName
)
{
if
(
type
.
isArray
())
{
appendType
(
sb
,
type
.
getComponentType
(),
useLongTypeName
);
sb
.
append
(
"[]"
);
}
else
{
sb
.
append
(
useLongTypeName
?
type
.
getName
()
:
type
.
getSimpleName
());
}
}
}
unififi-demo2-service/src/main/java/com/unififi/config/ControllerLogAdviceConfig.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
config
;
import
org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
@Configuration
public
class
ControllerLogAdviceConfig
{
@Value
(
"${unififi.controller-pointcut:execution(* com.unififi.controller.*.*(..))}"
)
private
String
pointcut
;
@Bean
@ConditionalOnMissingBean
(
UnififiProperties
.
class
)
UnififiProperties
unififiProperties
()
{
return
new
UnififiProperties
();
}
@Bean
public
AspectJExpressionPointcutAdvisor
configurabledvisor
(
UnififiProperties
unififiProperties
)
{
AspectJExpressionPointcutAdvisor
advisor
=
new
AspectJExpressionPointcutAdvisor
();
advisor
.
setExpression
(
pointcut
);
advisor
.
setAdvice
(
new
ControllerLogAdvice
(
unififiProperties
));
return
advisor
;
}
}
unififi-demo2-service/src/main/java/com/unififi/config/HttpMessageConverterConfig.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
config
;
import
com.alibaba.fastjson.JSON
;
import
com.alibaba.fastjson.serializer.SerializerFeature
;
import
com.alibaba.fastjson.support.config.FastJsonConfig
;
import
com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter
;
import
org.apache.commons.codec.Charsets
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.boot.autoconfigure.http.HttpMessageConverters
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.http.HttpInputMessage
;
import
org.springframework.http.HttpOutputMessage
;
import
org.springframework.http.MediaType
;
import
org.springframework.http.converter.HttpMessageNotReadableException
;
import
org.springframework.http.converter.HttpMessageNotWritableException
;
import
java.io.IOException
;
import
java.lang.reflect.Type
;
import
java.util.ArrayList
;
import
java.util.List
;
@Configuration
public
class
HttpMessageConverterConfig
{
@Bean
public
HttpMessageConverters
fastJsonHttpMessageConverters
()
{
FastJsonHttpMessageConverter
fastConverter
=
new
FastJsonHttpMessageConverter
();
FastJsonConfig
fastJsonConfig
=
new
FastJsonConfig
();
SerializerFeature
[]
serializerFeatures
=
new
SerializerFeature
[]{
// Date的日期转换器
SerializerFeature
.
WriteDateUseDateFormat
,
// 循环引用
SerializerFeature
.
DisableCircularReferenceDetect
};
fastJsonConfig
.
setSerializerFeatures
(
serializerFeatures
);
fastJsonConfig
.
setCharset
(
Charsets
.
UTF_8
);
fastConverter
.
setFastJsonConfig
(
fastJsonConfig
);
List
<
MediaType
>
fastjsonSupportedMediaTypes
=
new
ArrayList
<>();
fastjsonSupportedMediaTypes
.
add
(
MediaType
.
TEXT_PLAIN
);
fastjsonSupportedMediaTypes
.
add
(
MediaType
.
APPLICATION_JSON
);
fastConverter
.
setSupportedMediaTypes
(
fastjsonSupportedMediaTypes
);
return
new
HttpMessageConverters
(
fastConverter
);
}
private
static
class
UheFastJsonHttpMessageConverter
extends
FastJsonHttpMessageConverter
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
UheFastJsonHttpMessageConverter
.
class
);
@Override
public
Object
read
(
Type
type
,
Class
<?>
contextClass
,
HttpInputMessage
inputMessage
)
throws
IOException
,
HttpMessageNotReadableException
{
Object
obj
=
super
.
read
(
type
,
contextClass
,
inputMessage
);
if
(
logger
.
isInfoEnabled
())
{
logger
.
info
(
"U2C-REQ-[{}]:{}"
,
type
.
getTypeName
(),
JSON
.
toJSONString
(
obj
));
}
return
obj
;
}
@Override
public
void
write
(
Object
t
,
Type
type
,
MediaType
contentType
,
HttpOutputMessage
outputMessage
)
throws
IOException
,
HttpMessageNotWritableException
{
if
(
type
.
getTypeName
().
endsWith
(
"ListResp"
))
{
if
(
logger
.
isInfoEnabled
())
{
logger
.
info
(
"U2C-RESP-[{}]:{}"
,
type
.
getTypeName
(),
"LIST_IGNORE"
);
}
}
else
{
if
(
logger
.
isInfoEnabled
())
{
logger
.
info
(
"U2C-RESP-[{}]:{}"
,
type
.
getTypeName
(),
JSON
.
toJSONString
(
t
));
}
}
super
.
write
(
t
,
type
,
contentType
,
outputMessage
);
}
}
}
unififi-demo2-service/src/main/java/com/unififi/config/RestTemplateConfig.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
config
;
import
org.apache.http.client.HttpClient
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.http.client.BufferingClientHttpRequestFactory
;
import
org.springframework.http.client.ClientHttpRequestFactory
;
import
org.springframework.http.client.HttpComponentsClientHttpRequestFactory
;
import
org.springframework.web.client.RestTemplate
;
@Configuration
public
class
RestTemplateConfig
{
@Bean
public
ClientHttpRequestFactory
httpRequestFactory
(
HttpClient
httpClient
)
{
HttpComponentsClientHttpRequestFactory
httpComponentsClientHttpRequestFactory
=
new
HttpComponentsClientHttpRequestFactory
(
httpClient
);
httpComponentsClientHttpRequestFactory
.
setReadTimeout
(
5000
);
httpComponentsClientHttpRequestFactory
.
setConnectTimeout
(
30000
);
return
httpComponentsClientHttpRequestFactory
;
}
@Bean
public
RestTemplate
restTemplate
(
ClientHttpRequestFactory
httpRequestFactory
)
{
BufferingClientHttpRequestFactory
bufferingClientHttpRequestFactory
=
new
BufferingClientHttpRequestFactory
(
httpRequestFactory
);
RestTemplate
restTemplate
=
new
RestTemplate
(
bufferingClientHttpRequestFactory
);
restTemplate
.
getInterceptors
().
add
(
new
UnififiRestTemplateLogInterceptor
());
return
restTemplate
;
}
// @Bean
// public ClientHttpRequestFactory httpRequestFactory(HttpClient httpClient) {
// return new HttpComponentsClientHttpRequestFactory(httpClient);
// }
// @Bean
// public RestTemplateCustomizer restTemplateCustomizer(
// final ClientHttpRequestFactory requestFactory) {
// return restTemplate -> restTemplate
// .setRequestFactory(new BufferingClientHttpRequestFactory(requestFactory));
// }
}
unififi-demo2-service/src/main/java/com/unififi/config/ServiceExceptionAspect.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
config
;
import
com.unififi.model.User
;
import
org.aspectj.lang.ProceedingJoinPoint
;
import
org.aspectj.lang.annotation.Around
;
import
org.aspectj.lang.annotation.Aspect
;
import
org.aspectj.lang.annotation.Pointcut
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.stereotype.Component
;
@Aspect
@Component
public
class
ServiceExceptionAspect
{
private
final
static
Logger
logger
=
LoggerFactory
.
getLogger
(
"ServiceExceptionAspect"
);
@Pointcut
(
"execution(* com.unififi.service..*.*(..))"
)
public
void
printLog
()
{
}
@Around
(
"printLog()"
)
private
Object
doAround
(
ProceedingJoinPoint
pjp
)
{
try
{
return
pjp
.
proceed
();
}
catch
(
Throwable
throwable
)
{
logger
.
error
(
"ServiceException:"
,
throwable
);
User
u
=
new
User
();
u
.
setAge
(-
1
);
u
.
setName
(
throwable
.
getMessage
());
return
u
;
}
}
}
unififi-demo2-service/src/main/java/com/unififi/config/SwaggerConfig.java
View file @
d1f61698
...
...
@@ -22,7 +22,7 @@ public class SwaggerConfig {
@Value
(
"${swagger.enable:false}"
)
private
Boolean
enable
;
@Value
(
"${spring.cloud.nacos.discovery.metadata.unififi.
service.
version}"
)
@Value
(
"${spring.cloud.nacos.discovery.metadata.unififi.version}"
)
private
String
version
;
@Bean
...
...
unififi-demo2-service/src/main/java/com/unififi/config/UnififiProperties.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
config
;
import
org.springframework.boot.context.properties.ConfigurationProperties
;
import
org.springframework.context.annotation.Configuration
;
import
java.util.ArrayList
;
import
java.util.List
;
@Configuration
@ConfigurationProperties
(
ignoreInvalidFields
=
true
,
prefix
=
UnififiProperties
.
PREFIX
)
public
class
UnififiProperties
{
public
static
final
String
PREFIX
=
"unififi"
;
private
Logger
logger
=
new
Logger
();
private
Header
header
=
new
Header
();
private
String
controllerPointcut
=
""
;
public
Logger
getLogger
()
{
return
logger
;
}
public
void
setLogger
(
Logger
logger
)
{
this
.
logger
=
logger
;
}
public
Header
getHeader
()
{
return
header
;
}
public
void
setHeader
(
Header
header
)
{
this
.
header
=
header
;
}
public
String
getControllerPointcut
()
{
return
controllerPointcut
;
}
public
void
setControllerPointcut
(
String
controllerPointcut
)
{
this
.
controllerPointcut
=
controllerPointcut
;
}
public
static
class
Logger
{
private
Setting
feign
=
new
Setting
();
private
Setting
rest
=
new
Setting
();
private
Setting
controller
=
new
Setting
();
public
Setting
getFeign
()
{
return
feign
;
}
public
void
setFeign
(
Setting
feign
)
{
this
.
feign
=
feign
;
}
public
Setting
getRest
()
{
return
rest
;
}
public
void
setRest
(
Setting
rest
)
{
this
.
rest
=
rest
;
}
public
Setting
getController
()
{
return
controller
;
}
public
void
setController
(
Setting
controller
)
{
this
.
controller
=
controller
;
}
}
public
static
class
Header
{
private
List
<
String
>
throughNames
=
new
ArrayList
<>();
public
List
<
String
>
getThroughNames
()
{
return
throughNames
;
}
public
void
setThroughNames
(
List
<
String
>
throughNames
)
{
this
.
throughNames
=
throughNames
;
}
}
public
static
class
Setting
{
private
boolean
enabled
=
true
;
private
List
<
String
>
ignoreResponseDataMethodSigns
=
new
ArrayList
<>();
private
List
<
String
>
skipMethodSigns
=
new
ArrayList
<>();
private
boolean
showSpendms
=
false
;
public
boolean
isEnabled
()
{
return
enabled
;
}
public
void
setEnabled
(
boolean
enabled
)
{
this
.
enabled
=
enabled
;
}
public
List
<
String
>
getIgnoreResponseDataMethodSigns
()
{
return
ignoreResponseDataMethodSigns
;
}
public
void
setIgnoreResponseDataMethodSigns
(
List
<
String
>
ignoreResponseDataMethodSigns
)
{
this
.
ignoreResponseDataMethodSigns
=
ignoreResponseDataMethodSigns
;
}
public
List
<
String
>
getSkipMethodSigns
()
{
return
skipMethodSigns
;
}
public
void
setSkipMethodSigns
(
List
<
String
>
skipMethodSigns
)
{
this
.
skipMethodSigns
=
skipMethodSigns
;
}
public
boolean
isShowSpendms
()
{
return
showSpendms
;
}
public
void
setShowSpendms
(
boolean
showSpendms
)
{
this
.
showSpendms
=
showSpendms
;
}
}
}
unififi-demo2-service/src/main/java/com/unififi/config/UnififiRestTemplateLogInterceptor.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
config
;
import
org.apache.commons.codec.Charsets
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.http.HttpRequest
;
import
org.springframework.http.client.ClientHttpRequestExecution
;
import
org.springframework.http.client.ClientHttpRequestInterceptor
;
import
org.springframework.http.client.ClientHttpResponse
;
import
java.io.BufferedReader
;
import
java.io.IOException
;
import
java.io.InputStreamReader
;
import
java.net.URI
;
import
java.util.concurrent.TimeUnit
;
public
class
UnififiRestTemplateLogInterceptor
implements
ClientHttpRequestInterceptor
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
UnififiRestTemplateLogInterceptor
.
class
);
@Override
public
ClientHttpResponse
intercept
(
HttpRequest
request
,
byte
[]
body
,
ClientHttpRequestExecution
execution
)
throws
IOException
{
String
methodTag
=
getMethodTag
(
request
.
getURI
());
if
(
logger
.
isInfoEnabled
())
{
logger
.
info
(
"REST-REQ-[{}] {} --> {} {}"
,
methodTag
,
body
!=
null
?
new
String
(
body
,
Charsets
.
UTF_8
)
:
""
,
request
.
getMethod
(),
request
.
getURI
());
}
long
start
=
System
.
nanoTime
();
ClientHttpResponse
response
=
null
;
try
{
response
=
execution
.
execute
(
request
,
body
);
long
elapsedTime
=
TimeUnit
.
NANOSECONDS
.
toMillis
(
System
.
nanoTime
()
-
start
);
if
(
logger
.
isInfoEnabled
())
{
StringBuilder
inputStringBuilder
=
new
StringBuilder
();
try
(
BufferedReader
bufferedReader
=
new
BufferedReader
(
new
InputStreamReader
(
response
.
getBody
(),
Charsets
.
UTF_8
)))
{
String
line
=
bufferedReader
.
readLine
();
while
(
line
!=
null
)
{
inputStringBuilder
.
append
(
line
);
line
=
bufferedReader
.
readLine
();
if
(
line
!=
null
)
{
inputStringBuilder
.
append
(
'\n'
);
}
}
}
logger
.
info
(
"REST-RESP-[{}] {} {}ms"
,
methodTag
,
inputStringBuilder
.
toString
(),
elapsedTime
);
}
}
catch
(
IOException
ioe
)
{
logger
.
error
(
"REST-RESP-[{}] {}: {}"
,
methodTag
,
ioe
.
getClass
().
getSimpleName
(),
ioe
.
getMessage
());
throw
ioe
;
}
return
response
;
}
private
String
getMethodTag
(
URI
uri
)
{
try
{
if
(
uri
.
getPath
().
indexOf
(
'?'
)
>
-
1
)
{
return
uri
.
getPath
().
substring
(
0
,
uri
.
getPath
().
indexOf
(
'?'
));
}
else
{
return
uri
.
getPath
();
}
}
catch
(
Exception
e
)
{
return
uri
.
getPath
();
}
}
}
unififi-demo2-service/src/main/java/com/unififi/controller/Demo2Controller.java
View file @
d1f61698
...
...
@@ -32,7 +32,8 @@ public class Demo2Controller implements UserApi {
@Override
@RequestMapping
(
value
=
"/echo/{string}"
,
method
=
RequestMethod
.
GET
)
public
String
echo
(
@PathVariable
String
string
)
{
return
userService
.
echo
(
string
);
// return userService.echo(string);
return
"unififi-demo2-service echo: "
+
string
;
}
@Override
...
...
@@ -58,13 +59,14 @@ public class Demo2Controller implements UserApi {
public
User
get
(
@RequestParam
(
"name"
)
String
name
,
@RequestParam
(
"age"
)
Integer
age
)
{
log
.
info
(
"user/get. name:{}, age:{}"
,
name
,
age
);
log
.
info
(
"header. token:{}"
,
request
.
getHeader
(
"Authorization"
));
try
{
Thread
.
sleep
(
3000L
);
}
catch
(
InterruptedException
e
)
{
e
.
printStackTrace
();
}
//
try {
//
Thread.sleep(3000L);
//
} catch (InterruptedException e) {
//
e.printStackTrace();
//
}
User
user
=
userService
.
get
(
name
);
user
.
setBirthday
(
new
Date
());
log
.
info
(
"user.birthdy:{}"
,
user
.
getBirthday
());
return
user
;
}
...
...
@@ -76,7 +78,7 @@ public class Demo2Controller implements UserApi {
@Override
@PostMapping
(
value
=
"/getUser"
,
produces
=
MediaType
.
APPLICATION_JSON_VALUE
,
consumes
=
MediaType
.
APPLICATION_JSON_VALUE
)
public
User
getUser
(
@RequestBody
User
user
)
{
log
.
info
(
"demo2 getUser. name:{}"
,
user
.
getName
(
));
log
.
info
(
"demo2 getUser. name:{}"
,
JSON
.
toJSONString
(
user
));
return
userService
.
get
(
user
.
getName
());
}
...
...
unififi-demo2-service/src/main/java/com/unififi/service/impl/UserServiceImpl.java
View file @
d1f61698
...
...
@@ -15,10 +15,7 @@ import org.springframework.http.*;
import
org.springframework.stereotype.Service
;
import
org.springframework.web.client.RestTemplate
;
import
java.util.ArrayList
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.*
;
@Slf4j
@Service
...
...
@@ -75,6 +72,7 @@ public class UserServiceImpl implements UserService {
DemoUser
userEntity
=
demoUserMapper
.
selectOne
(
queryWrapper
);
User
user
=
new
User
();
BeanUtils
.
copyProperties
(
userEntity
,
user
);
user
.
setBirthday
(
new
Date
());
return
user
;
}
...
...
unififi-demo2-service/src/main/resources/bootstrap.yml
View file @
d1f61698
...
...
@@ -35,5 +35,8 @@ spring:
#ip: 39.106.6.98
metadata
:
unififi.env
:
${spring.profiles.active:}
unififi.
service.
version
:
'
@unififi-service.version@'
unififi.version
:
'
@unififi-service.version@'
user.home
:
${user.home}
unififi
:
timezone
:
enabled
:
true
\ No newline at end of file
unififi-demo2-service/src/main/resources/logback-spring.xml
View file @
d1f61698
...
...
@@ -8,7 +8,7 @@
<appender
name=
"STDOUT"
class=
"ch.qos.logback.core.ConsoleAppender"
>
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level %logger - %msg%n
</pattern>
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %
X{unififi-requestId} %
level %logger - %msg%n
</pattern>
</encoder>
</appender>
...
...
@@ -21,7 +21,7 @@
</rollingPolicy>
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level - %msg%n
</pattern>
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %
X{unififi-requestId} %
level - %msg%n
</pattern>
</encoder>
</appender>
...
...
unififi-gateway/pom.xml
View file @
d1f61698
This diff is collapsed.
Click to expand it.
unififi-gateway/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java
0 → 100644
View file @
d1f61698
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package
com
.
alibaba
.
cloud
.
sentinel
.
datasource
.
config
;
import
com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean
;
import
org.springframework.util.StringUtils
;
import
javax.validation.constraints.NotEmpty
;
/**
* Nacos Properties class Using by {@link DataSourcePropertiesConfiguration} and
* {@link NacosDataSourceFactoryBean}.
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public
class
NacosDataSourceProperties
extends
AbstractDataSourceProperties
{
private
String
serverAddr
;
/**
* the nacos authentication username.
*/
private
String
username
;
/**
* the nacos authentication password.
*/
private
String
password
;
@NotEmpty
private
String
groupId
=
"DEFAULT_GROUP"
;
@NotEmpty
private
String
dataId
;
private
String
endpoint
;
private
String
namespace
;
private
String
accessKey
;
private
String
secretKey
;
public
NacosDataSourceProperties
()
{
super
(
NacosDataSourceFactoryBean
.
class
.
getName
());
}
@Override
public
void
preCheck
(
String
dataSourceName
)
{
if
(
StringUtils
.
isEmpty
(
serverAddr
))
{
serverAddr
=
this
.
getEnv
().
getProperty
(
"spring.cloud.sentinel.datasource.nacos.server-addr"
,
"localhost:8848"
);
}
}
public
String
getServerAddr
()
{
return
serverAddr
;
}
public
void
setServerAddr
(
String
serverAddr
)
{
this
.
serverAddr
=
serverAddr
;
}
public
String
getGroupId
()
{
return
groupId
;
}
public
void
setGroupId
(
String
groupId
)
{
this
.
groupId
=
groupId
;
}
public
String
getDataId
()
{
return
dataId
;
}
public
void
setDataId
(
String
dataId
)
{
this
.
dataId
=
dataId
;
}
public
String
getEndpoint
()
{
return
endpoint
;
}
public
void
setEndpoint
(
String
endpoint
)
{
this
.
endpoint
=
endpoint
;
}
public
String
getNamespace
()
{
return
namespace
;
}
public
void
setNamespace
(
String
namespace
)
{
this
.
namespace
=
namespace
;
}
public
String
getAccessKey
()
{
return
accessKey
;
}
public
void
setAccessKey
(
String
accessKey
)
{
this
.
accessKey
=
accessKey
;
}
public
String
getSecretKey
()
{
return
secretKey
;
}
public
void
setSecretKey
(
String
secretKey
)
{
this
.
secretKey
=
secretKey
;
}
public
String
getUsername
()
{
return
username
;
}
public
void
setUsername
(
String
username
)
{
this
.
username
=
username
;
}
public
String
getPassword
()
{
return
password
;
}
public
void
setPassword
(
String
password
)
{
this
.
password
=
password
;
}
}
unififi-gateway/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/NacosDataSourceFactoryBean.java
0 → 100644
View file @
d1f61698
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package
com
.
alibaba
.
cloud
.
sentinel
.
datasource
.
factorybean
;
import
com.alibaba.csp.sentinel.datasource.Converter
;
import
com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource
;
import
com.alibaba.nacos.api.PropertyKeyConst
;
import
org.springframework.beans.factory.FactoryBean
;
import
org.springframework.util.StringUtils
;
import
java.util.Properties
;
/**
* A {@link FactoryBean} for creating {@link NacosDataSource} instance.
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see NacosDataSource
*/
public
class
NacosDataSourceFactoryBean
implements
FactoryBean
<
NacosDataSource
>
{
private
String
serverAddr
;
/**
* the nacos authentication username.
*/
private
String
username
;
/**
* the nacos authentication password.
*/
private
String
password
;
private
String
groupId
;
private
String
dataId
;
private
Converter
converter
;
private
String
endpoint
;
private
String
namespace
;
private
String
accessKey
;
private
String
secretKey
;
@Override
public
NacosDataSource
getObject
()
throws
Exception
{
Properties
properties
=
new
Properties
();
if
(!
StringUtils
.
isEmpty
(
this
.
serverAddr
))
{
properties
.
setProperty
(
PropertyKeyConst
.
SERVER_ADDR
,
this
.
serverAddr
);
properties
.
setProperty
(
PropertyKeyConst
.
USERNAME
,
this
.
username
);
properties
.
setProperty
(
PropertyKeyConst
.
PASSWORD
,
this
.
password
);
}
else
{
properties
.
setProperty
(
PropertyKeyConst
.
ACCESS_KEY
,
this
.
accessKey
);
properties
.
setProperty
(
PropertyKeyConst
.
SECRET_KEY
,
this
.
secretKey
);
properties
.
setProperty
(
PropertyKeyConst
.
ENDPOINT
,
this
.
endpoint
);
}
if
(!
StringUtils
.
isEmpty
(
this
.
namespace
))
{
properties
.
setProperty
(
PropertyKeyConst
.
NAMESPACE
,
this
.
namespace
);
}
return
new
NacosDataSource
(
properties
,
groupId
,
dataId
,
converter
);
}
@Override
public
Class
<?>
getObjectType
()
{
return
NacosDataSource
.
class
;
}
public
String
getServerAddr
()
{
return
serverAddr
;
}
public
void
setServerAddr
(
String
serverAddr
)
{
this
.
serverAddr
=
serverAddr
;
}
public
String
getGroupId
()
{
return
groupId
;
}
public
void
setGroupId
(
String
groupId
)
{
this
.
groupId
=
groupId
;
}
public
String
getDataId
()
{
return
dataId
;
}
public
void
setDataId
(
String
dataId
)
{
this
.
dataId
=
dataId
;
}
public
Converter
getConverter
()
{
return
converter
;
}
public
void
setConverter
(
Converter
converter
)
{
this
.
converter
=
converter
;
}
public
String
getEndpoint
()
{
return
endpoint
;
}
public
void
setEndpoint
(
String
endpoint
)
{
this
.
endpoint
=
endpoint
;
}
public
String
getNamespace
()
{
return
namespace
;
}
public
void
setNamespace
(
String
namespace
)
{
this
.
namespace
=
namespace
;
}
public
String
getAccessKey
()
{
return
accessKey
;
}
public
void
setAccessKey
(
String
accessKey
)
{
this
.
accessKey
=
accessKey
;
}
public
String
getSecretKey
()
{
return
secretKey
;
}
public
void
setSecretKey
(
String
secretKey
)
{
this
.
secretKey
=
secretKey
;
}
public
String
getUsername
()
{
return
username
;
}
public
void
setUsername
(
String
username
)
{
this
.
username
=
username
;
}
public
String
getPassword
()
{
return
password
;
}
public
void
setPassword
(
String
password
)
{
this
.
password
=
password
;
}
}
unififi-gateway/src/main/java/com/unififi/GatewayApplication.java
0 → 100644
View file @
d1f61698
package
com
.
unififi
;
import
com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
import
org.springframework.cloud.client.discovery.EnableDiscoveryClient
;
import
org.springframework.cloud.openfeign.EnableFeignClients
;
import
org.springframework.context.ApplicationContext
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.RestController
;
@SpringBootApplication
(
scanBasePackages
=
{
"com.u2c"
,
"com.unififi"
})
@EnableDiscoveryClient
@EnableFeignClients
(
basePackages
=
{
"com.u2c"
,
"com.unififi"
})
@RestController
public
class
GatewayApplication
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
GatewayApplication
.
class
);
public
static
void
main
(
String
[]
args
)
{
logger
.
info
(
"Application starting..."
);
ApplicationContext
ac
=
SpringApplication
.
run
(
GatewayApplication
.
class
,
args
);
Runtime
.
getRuntime
().
addShutdownHook
(
new
Thread
()
{
@Override
public
void
run
()
{
logger
.
info
(
"Application ShutdownHook..."
);
NacosAutoServiceRegistration
nacosAutoServiceRegistration
=
ac
.
getBean
(
NacosAutoServiceRegistration
.
class
);
if
(
nacosAutoServiceRegistration
!=
null
)
{
nacosAutoServiceRegistration
.
stop
();
}
}
});
}
@GetMapping
(
"/hello"
)
public
String
hello
()
{
return
"hello sentinel"
;
}
}
unififi-gateway/src/main/java/com/unififi/config/GatewayConfiguration.java
0 → 100644
View file @
d1f61698
package
com
.
unififi
.
config
;
import
org.springframework.cloud.gateway.filter.ratelimit.KeyResolver
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
reactor.core.publisher.Mono
;
/**
* @author lihaipeng
* @date 2020-09-23
*/
@Configuration
public
class
GatewayConfiguration
{
// private final List<ViewResolver> viewResolvers;
// private final ServerCodecConfigurer serverCodecConfigurer;
//
// public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
// ServerCodecConfigurer serverCodecConfigurer) {
// this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
// this.serverCodecConfigurer = serverCodecConfigurer;
// }
//
// @Bean
// @Order(Ordered.HIGHEST_PRECEDENCE)
// public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
// // Register the block exception handler for Spring Cloud Gateway.
// return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
// }
//
// @Bean
// @Order(Ordered.HIGHEST_PRECEDENCE)
// public GlobalFilter sentinelGatewayFilter() {
// return new SentinelGatewayFilter();
// }
//
// @PostConstruct
// public void doInit() {
// initCustomizedApis();
// initGatewayRules();
// }
//
// private void initCustomizedApis() {
// Set<ApiDefinition> definitions = new HashSet<>();
// ApiDefinition api1 = new ApiDefinition("some_customized_api")
// .setPredicateItems(new HashSet<ApiPredicateItem>() {{
// add(new ApiPathPredicateItem().setPattern("/ahas"));
// add(new ApiPathPredicateItem().setPattern("/product/**")
// .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
// }});
// ApiDefinition api2 = new ApiDefinition("another_customized_api")
// .setPredicateItems(new HashSet<ApiPredicateItem>() {{
// add(new ApiPathPredicateItem().setPattern("/**")
// .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
// }});
// definitions.add(api1);
// definitions.add(api2);
// GatewayApiDefinitionManager.loadApiDefinitions(definitions);
// }
//
// private void initGatewayRules() {
// Set<GatewayFlowRule> rules = new HashSet<>();
// rules.add(new GatewayFlowRule("aliyun_route")
// .setCount(10)
// .setIntervalSec(1)
// );
// rules.add(new GatewayFlowRule("aliyun_route")
// .setCount(2)
// .setIntervalSec(2)
// .setBurst(2)
// .setParamItem(new GatewayParamFlowItem()
// .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
// )
// );
// rules.add(new GatewayFlowRule("httpbin_route")
// .setCount(10)
// .setIntervalSec(1)
// .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
// .setMaxQueueingTimeoutMs(600)
// .setParamItem(new GatewayParamFlowItem()
// .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
// .setFieldName("X-Sentinel-Flag")
// )
// );
// rules.add(new GatewayFlowRule("httpbin_route")
// .setCount(1)
// .setIntervalSec(1)
// .setParamItem(new GatewayParamFlowItem()
// .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
// .setFieldName("pa")
// )
// );
// rules.add(new GatewayFlowRule("httpbin_route")
// .setCount(2)
// .setIntervalSec(30)
// .setParamItem(new GatewayParamFlowItem()
// .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
// .setFieldName("type")
// .setPattern("warn")
// .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)
// )
// );
//
// rules.add(new GatewayFlowRule("some_customized_api")
// .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
// .setCount(5)
// .setIntervalSec(1)
// .setParamItem(new GatewayParamFlowItem()
// .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
// .setFieldName("pn")
// )
// );
// GatewayRuleManager.loadRules(rules);
// }
@Bean
KeyResolver
ipKeyResolver
()
{
return
exchange
->
Mono
.
just
(
exchange
.
getRequest
().
getRemoteAddress
().
getHostName
());
}
}
\ No newline at end of file
unififi-gateway/src/main/java/com/unififi/config/UnififiGatewayProperties.java
0 → 100644
View file @
d1f61698
package
com
.
unififi
.
config
;
import
org.springframework.boot.context.properties.ConfigurationProperties
;
import
org.springframework.cloud.context.config.annotation.RefreshScope
;
import
org.springframework.context.annotation.Configuration
;
import
java.util.HashMap
;
import
java.util.Map
;
@Configuration
@RefreshScope
@ConfigurationProperties
(
ignoreInvalidFields
=
true
,
prefix
=
UnififiGatewayProperties
.
PREFIX
)
public
class
UnififiGatewayProperties
{
public
static
final
String
PREFIX
=
"unififi.gateway"
;
private
String
basicService
=
"u2c-basic-service"
;
private
Map
<
String
,
String
>
pathPermMap
=
new
HashMap
<>();
public
String
getBasicService
()
{
return
basicService
;
}
public
void
setBasicService
(
String
basicService
)
{
this
.
basicService
=
basicService
;
}
public
Map
<
String
,
String
>
getPathPermMap
()
{
return
pathPermMap
;
}
public
void
setPathPermMap
(
Map
<
String
,
String
>
pathPermMap
)
{
this
.
pathPermMap
=
pathPermMap
;
}
}
unififi-gateway/src/main/java/com/unififi/constant/Constants.java
0 → 100644
View file @
d1f61698
package
com
.
unififi
.
constant
;
public
class
Constants
{
public
static
final
String
AUTHORIZATION
=
"Authorization"
;
public
static
final
String
UTF8
=
"UTF-8"
;
public
static
final
String
UNKNOWN
=
"unknown"
;
public
static
final
String
SLASH
=
"/"
;
public
static
final
String
COLON
=
":"
;
public
static
final
String
LINE
=
"-"
;
public
static
final
String
HEADER_RESPONSE_REQUESTID
=
"requestId"
;
}
unififi-gateway/src/main/java/com/unififi/filter/AuthenticationFilter.java
0 → 100644
View file @
d1f61698
package
com
.
unififi
.
filter
;
import
lombok.extern.slf4j.Slf4j
;
import
org.reactivestreams.Publisher
;
import
org.springframework.cloud.gateway.filter.GatewayFilterChain
;
import
org.springframework.cloud.gateway.filter.GlobalFilter
;
import
org.springframework.core.Ordered
;
import
org.springframework.core.io.buffer.DataBuffer
;
import
org.springframework.core.io.buffer.DataBufferFactory
;
import
org.springframework.core.io.buffer.DataBufferUtils
;
import
org.springframework.http.server.reactive.ServerHttpResponse
;
import
org.springframework.http.server.reactive.ServerHttpResponseDecorator
;
import
org.springframework.stereotype.Component
;
import
org.springframework.web.server.ServerWebExchange
;
import
reactor.core.publisher.Flux
;
import
reactor.core.publisher.Mono
;
import
java.nio.charset.Charset
;
@Component
@Slf4j
public
class
AuthenticationFilter
implements
GlobalFilter
,
Ordered
{
// @Autowired
// private BasicClient basicClient;
// @Autowired
// private UnififiProperties unififiProperties;
// @Autowired
// private UnififiGatewayProperties unififiGatewayProperties;
@Override
public
Mono
<
Void
>
filter
(
ServerWebExchange
exchange
,
GatewayFilterChain
chain
)
{
// exchange.getResponse().getHeaders().add(Constants.HEADER_RESPONSE_REQUESTID, exchange.getRequest().getId());
// String url = exchange.getRequest().getURI().getPath();
// if (url.indexOf(unififiGatewayProperties.getBasicService()) > -1) {
// return chain.filter(exchange);
// }
// String token = exchange.getRequest().getHeaders().getFirst(Constants.AUTHORIZATION);
// if (StringUtils.isEmpty(token)) {
// exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
// return exchange.getResponse().setComplete();
// }
// try {
// String permission = url.substring(1).replaceAll(Constants.SLASH, Constants.LINE);
// String pathPerm = unififiGatewayProperties.getPathPermMap().get(permission);
// if (!StringUtils.isEmpty(pathPerm)) {
// permission = pathPerm;
// }
// AuthenticateRsp authorizationRsp = basicClient.authenticate(permission, token);
// if (authorizationRsp == null || authorizationRsp.getCode() != 200 || authorizationRsp.getUser() == null) {
// exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
// return exchange.getResponse().setComplete();
// }
// if (authorizationRsp.getUser().getGray() == null) {
// authorizationRsp.getUser().setGray("");
// }
// Consumer<HttpHeaders> httpHeaders = httpHeader -> {
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_REQUESTID, exchange.getRequest().getId());
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_USERNAME, authorizationRsp.getUser().getUserName());
// try {
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_NIKENAME, URLEncoder.encode(authorizationRsp.getUser().getNikeName(), Constants.UTF8));
// } catch (UnsupportedEncodingException e) {
// }
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_USERID, String.valueOf(authorizationRsp.getUser().getUserId()));
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_DEPTID, String.valueOf(authorizationRsp.getUser().getDeptId()));
// try {
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_DEPTNAME, URLEncoder.encode(authorizationRsp.getUser().getDeptName(), Constants.UTF8));
// } catch (UnsupportedEncodingException e) {
// }
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_DEPTLEADER, authorizationRsp.getUser().getDeptLeader());
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_COUNTRY, authorizationRsp.getUser().getCountry());
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_TIMEZONE, authorizationRsp.getUser().getTimeZone());
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_LANGUAGE, authorizationRsp.getUser().getLanguage());
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_CURRENCY, authorizationRsp.getUser().getCurrency());
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_POSTCODE, authorizationRsp.getUser().getPostCode());
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_DATASCOPE, authorizationRsp.getUser().getDataScope());
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_GRAYSCALE, authorizationRsp.getUser().getGray());
// if (!CollectionUtils.isEmpty(authorizationRsp.getUser().getDataScopeDeptIds())) {
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_DATASCOPEDEPTIDS, org.apache.commons.lang3.StringUtils.join(authorizationRsp.getUser().getDataScopeDeptIds(), ","));
// }
// if (!CollectionUtils.isEmpty(authorizationRsp.getUser().getPaymentTypes())) {
// httpHeader.set(ServletUtils.HEADER_KEY_UNIFIFI_PAYMENTTYPES, org.apache.commons.lang3.StringUtils.join(authorizationRsp.getUser().getPaymentTypes(), ","));
// }
// if (unififiProperties.getLoadbalancer().isGray()) {
// UnififiContextHolder.getCurrentContext().add(ServletUtils.HEADER_KEY_UNIFIFI_USERNAME, authorizationRsp.getUser().getUserName());
// UnififiContextHolder.getCurrentContext().add(ServletUtils.HEADER_KEY_UNIFIFI_GRAYSCALE, authorizationRsp.getUser().getGray());
// }
// };
// ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders).build();
// return chain.filter(exchange.mutate().request(serverHttpRequest).build());
// } catch (Exception e) {
// log.error("Exception[AuthenticationFilter]:", e);
// exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
// return exchange.getResponse().setComplete();
// }
// return chain.filter(exchange);
ServerHttpResponse
originalResponse
=
exchange
.
getResponse
();
DataBufferFactory
bufferFactory
=
originalResponse
.
bufferFactory
();
ServerHttpResponseDecorator
decoratedResponse
=
new
ServerHttpResponseDecorator
(
originalResponse
)
{
@Override
public
Mono
<
Void
>
writeWith
(
Publisher
<?
extends
DataBuffer
>
body
)
{
if
(
body
instanceof
Flux
)
{
Flux
<?
extends
DataBuffer
>
fluxBody
=
(
Flux
<?
extends
DataBuffer
>)
body
;
return
super
.
writeWith
(
fluxBody
.
map
(
dataBuffer
->
{
// probably should reuse buffers
byte
[]
content
=
new
byte
[
dataBuffer
.
readableByteCount
()];
dataBuffer
.
read
(
content
);
//释放掉内存
DataBufferUtils
.
release
(
dataBuffer
);
String
s
=
new
String
(
content
,
Charset
.
forName
(
"UTF-8"
));
log
.
info
(
"{}"
,
s
);
//TODO,s就是response的值,想修改、查看就随意而为了
byte
[]
uppedContent
=
new
String
(
content
,
Charset
.
forName
(
"UTF-8"
)).
getBytes
();
return
bufferFactory
.
wrap
(
uppedContent
);
}));
}
// if body is not a flux. never got there.
return
super
.
writeWith
(
body
);
}
};
// replace response with decorator
return
chain
.
filter
(
exchange
.
mutate
().
response
(
decoratedResponse
).
build
());
}
@Override
public
int
getOrder
()
{
return
-
100
;
}
}
unififi-gateway/src/main/java/com/unififi/gateway/GatewayApplication.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
gateway
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
import
org.springframework.cloud.openfeign.EnableFeignClients
;
import
org.springframework.web.bind.annotation.RestController
;
@RestController
@SpringBootApplication
@EnableFeignClients
public
class
GatewayApplication
{
public
static
void
main
(
String
[]
args
)
{
SpringApplication
.
run
(
GatewayApplication
.
class
,
args
);
}
}
unififi-gateway/src/main/java/com/unififi/gateway/filter/AuthenticationFilter.java
deleted
100644 → 0
View file @
d92e6fae
package
com
.
unififi
.
gateway
.
filter
;
import
org.springframework.cloud.gateway.filter.GatewayFilterChain
;
import
org.springframework.cloud.gateway.filter.GlobalFilter
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.web.server.ServerWebExchange
;
import
reactor.core.publisher.Mono
;
public
class
AuthenticationFilter
implements
GlobalFilter
{
@Override
public
Mono
<
Void
>
filter
(
ServerWebExchange
exchange
,
GatewayFilterChain
chain
)
{
chain
.
filter
(
exchange
)
.
then
(
Mono
.
just
(
exchange
))
.
map
(
serverWebExchange
->
{
//adds header to response
serverWebExchange
.
getResponse
().
getHeaders
().
set
(
"CUSTOM-RESPONSE-HEADER"
,
HttpStatus
.
OK
.
equals
(
serverWebExchange
.
getResponse
().
getStatusCode
())
?
"It worked"
:
"It did not work"
);
return
serverWebExchange
;
})
.
then
();
return
null
;
}
}
unififi-gateway/src/main/resources/application.yml
→
unififi-gateway/src/main/resources/application.yml
_bak
View file @
d1f61698
...
...
@@ -38,4 +38,4 @@ spring:
response-timeout: 30000
unififi-demo2-service:
ribbon:
NFLoadBalancerRuleClassName
:
com.netflix.loadbalancer.RoundRobinRule
\ No newline at end of file
NFLoadBalancerRuleClassName: com.unififi.loadbalancer.UnififiRule
\ No newline at end of file
unififi-gateway/src/main/resources/bootstrap.yml
View file @
d1f61698
server
:
port
:
18082
compression
:
enabled
:
true
min-response-size
:
2048
mime-types
:
'
application/json'
shutdown
:
graceful
management
:
endpoints
:
web
:
exposure
:
include
:
'
*'
endpoint
:
gateway
:
enabled
:
true
health
:
show-details
:
always
spring
:
lifecycle
:
timeout-per-shutdown-phase
:
60s
application
:
name
:
unififi-gateway
cloud
:
nacos
:
username
:
nacos
password
:
nacos
server-addr
:
localhost:8848
server-addr
:
39.106.6.97:8848
config
:
file-extension
:
yaml
shared-configs
:
-
data-id
:
unififi-common.yaml
refresh
:
false
group
:
DEFAULT_GROUP
-
data-id
:
unififi-redis.yaml
refresh
:
false
group
:
DEFAULT_GROUP
discovery
:
metadata
:
unififi.mode
:
${unififi.mode:}
unififi.env
:
${spring.profiles.active:}
unififi.version
:
'
@unififi-gateway.version@'
user.home
:
${user.home}
sentinel
:
scg
:
fallback
:
mode
:
response
response-body
:
'
{"status:":219}'
filter
:
enabled
:
false
eager
:
true
transport
:
port
:
8719
dashboard
:
39.106.6.97:8849
datasource
:
ds1
:
nacos
:
username
:
nacos
password
:
nacos
server-addr
:
39.106.6.97:8848
dataId
:
${spring.application.name}-sentinel.json
groupId
:
DEFAULT_GROUP
data-type
:
json
rule-type
:
gw-flow
gateway
:
httpclient
:
connect-timeout
:
5000
response-timeout
:
60s
enabled
:
true
actuator
:
verbose
:
enabled
:
true
discovery
:
locator
:
# enabled: true
lower-case-service-id
:
true
routes
:
-
id
:
aliyun_route
uri
:
https://www.aliyun.com/
predicates
:
-
Path=/product/**
-
id
:
httpbin_route
uri
:
https://httpbin.org
predicates
:
-
Path=/httpbin/**
filters
:
-
RewritePath=/httpbin/(?<segment>.*), /$\{segment}
-
id
:
baidu_route
uri
:
https://www.baidu.com
predicates
:
-
Path=/baidu/**
filters
:
-
StripPrefix=1
-
name
:
RequestRateLimiter
args
:
redis-rate-limiter.replenishRate
:
1
redis-rate-limiter.burstCapacity
:
1
key-resolver
:
"
#{@ipKeyResolver}"
-
id
:
unififi-demo2-service_route
uri
:
lb://unififi-demo2-service
predicates
:
-
Path=/unififi-demo2-service/**
filters
:
-
StripPrefix=1
# - name: RequestRateLimiter
# args:
# redis-rate-limiter.replenishRate: 1
# redis-rate-limiter.burstCapacity: 1
# key-resolver: "#{@ipKeyResolver}"
unififi-demo1-service
:
ribbon
:
NFLoadBalancerRuleClassName
:
com.unififi.loadbalancer.UnififiRule
#NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule
unififi-demo2-service
:
ribbon
:
NFLoadBalancerRuleClassName
:
com.unififi.loadbalancer.UnififiRule
unififi
:
type
:
gateway
loadbalancer
:
gray
:
true
same-cluster
:
true
rule
:
RandomWeight
gateway
:
path-perm-map
:
unififi-demo1-service-user-get
:
user:get
unififi-demo2-service-user-get
:
user:get
timezone
:
enabled
:
true
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment