Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

integration transport module with spring-mvc #1957

Merged
merged 20 commits into from
Feb 23, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
1ba3a7b
integration transport module with spring-mvc
shenbaoyong Jan 8, 2021
c5160e8
fix review for #1957
shenbaoyong Jan 16, 2021
d54c2e6
fix review for #1957 code format & triggerSentinelInit
shenbaoyong Jan 23, 2021
24e89cf
fix pr1957 review problem
shenbaoyong Jan 30, 2021
3469fd9
dashboard: Fix issue of memory leak in real-time monitoring page (#1905)
zhangkai253 Dec 28, 2020
a7f3682
Support setting flush interval of the metric log via SentinelConfig p…
brotherlu-xcq Dec 31, 2020
7fe09ff
Refactor SpiLoader and enhance SPI mechanism (#1383)
cdfive Jan 27, 2021
e1540d1
dashboard: authFilterExcludeUrls supports matching path pattern like …
brotherlu-xcq Jan 27, 2021
cf4f364
Improve MetricFetcher under concurrent conditions (#1918)
samuelllin Jan 28, 2021
ebedd6d
dependency: Upgrade fastjson to 1.2.75 (#2006)
liuming-dev Feb 2, 2021
82d2818
dependency: Upgrade snakeyaml to 1.26 in sentinel-cluster-server-envo…
liuming-dev Feb 3, 2021
643850d
Improve RocketMQ integration example (#1757)
PeineLiang Feb 3, 2021
d372ff9
Remove unused code (#1991)
zhouyongshen Feb 4, 2021
a66bc2b
Update source/target JDK version to 1.8 and update documents
sczyh30 Feb 1, 2021
149cf88
Use JDK 1.8 native LongAdder instead and remove legacy LongAdder
sczyh30 Feb 1, 2021
c291c33
Polish SpiLoader and SentinelConfig
sczyh30 Feb 4, 2021
5d63417
Bump version to 1.8.1
sczyh30 Feb 4, 2021
efcda7e
Bump version to 1.8.2-SNAPSHOT
sczyh30 Feb 4, 2021
6cc8684
fix pr1957 review spi-order
shenbaoyong Feb 5, 2021
4ab9f41
fix transport-spring-mvc version
shenbaoyong Feb 5, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions sentinel-transport/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@

<module>sentinel-transport-simple-http</module>
<module>sentinel-transport-netty-http</module>
<module>sentinel-transport-spring-mvc</module>
</modules>
</project>
48 changes: 48 additions & 0 deletions sentinel-transport/sentinel-transport-spring-mvc/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>sentinel-transport</artifactId>
<groupId>com.alibaba.csp</groupId>
<version>1.8.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>sentinel-transport-spring-mvc</artifactId>

<properties>
<apache.httpclient.version>4.5.3</apache.httpclient.version>
<servlet.api.version>3.1.0</servlet.api.version>
<spring.version>5.1.8.RELEASE</spring.version>
</properties>

<dependencies>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${apache.httpclient.version}</version>
</dependency>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about making spring-webmvc,javax.servlet-api scope provided, since user may use different version of spring or spring-boot, the version may conflicts. Another way is that user can exclude them manually.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes I will change their scope to provided

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tend to create new demo module. I think sentinel-transport-spring-mvc and sentinel-spring-webmvc-adapter have different focus, it is better to separate.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It had a point, a separate demo will make it easier for new users to understand how to use this new module.

</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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
*
* http://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.csp.sentinel.transport.command;

import com.alibaba.csp.sentinel.command.CommandHandler;
import com.alibaba.csp.sentinel.command.CommandRequest;
import com.alibaba.csp.sentinel.command.CommandResponse;
import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.transport.command.http.StatusCode;
import com.alibaba.csp.sentinel.transport.log.CommandCenterLog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
* @author shenbaoyong
*/
public class SentinelApiHandler {

public static final String SERVER_ERROR_MESSAGE = "Command server error";
public static final String INVALID_COMMAND_MESSAGE = "Invalid command";

private CommandHandler commandHandler;

public SentinelApiHandler(CommandHandler commandHandler) {
this.commandHandler = commandHandler;
}

public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
PrintWriter printWriter = null;
try {
long start = System.currentTimeMillis();
printWriter = httpServletResponse.getWriter();
CommandCenterLog.info("[SentinelApiHandler] request income: " + httpServletRequest.getRequestURL());
CommandRequest request = new CommandRequest();
Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
String[] value = entry.getValue();
if(value != null && value.length >= 1){
request.addParam(entry.getKey(), value[0]);
}
}
if (commandHandler == null) {
writeResponse(httpServletResponse, printWriter, StatusCode.BAD_REQUEST, INVALID_COMMAND_MESSAGE);
return;
}
CommandResponse<?> response = commandHandler.handle(request);
handleResponse(response, httpServletResponse, printWriter);

long cost = System.currentTimeMillis() - start;
CommandCenterLog.info("[SentinelApiHandler] Deal request : " + httpServletRequest.getRequestURL()
+ ", time cost: " + cost + " ms");
} catch (Throwable e) {
CommandCenterLog.warn("[SentinelApiHandler] error", e);
try {
if(printWriter != null){
String errorMessage = SERVER_ERROR_MESSAGE;
e.printStackTrace();
writeResponse(httpServletResponse, printWriter, StatusCode.INTERNAL_SERVER_ERROR, errorMessage);
}
} catch (Exception e1) {
CommandCenterLog.warn("Failed to write error response", e1);
}
} finally {

}
}

private void writeResponse(HttpServletResponse httpServletResponse, PrintWriter out, StatusCode statusCode, String message) {
httpServletResponse.setStatus(statusCode.getCode());
if (message != null) {
out.print(message);
}
out.flush();
}

private <T> void handleResponse(CommandResponse<T> response, HttpServletResponse httpServletResponse, final PrintWriter printWriter) throws Exception {
if (response.isSuccess()) {
if (response.getResult() == null) {
writeResponse(httpServletResponse, printWriter, StatusCode.OK, null);
return;
}
// Here we directly use `toString` to encode the result to plain text.
byte[] buffer = response.getResult().toString().getBytes(SentinelConfig.charset());
writeResponse(httpServletResponse, printWriter, StatusCode.OK, new String(buffer));
} else {
String msg = SERVER_ERROR_MESSAGE;
if (response.getException() != null) {
msg = response.getException().getMessage();
}
writeResponse(httpServletResponse, printWriter, StatusCode.BAD_REQUEST, msg);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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
*
* http://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.csp.sentinel.transport.command;

import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author shenbaoyong
*/
public class SentinelApiHandlerAdapter implements HandlerAdapter, Ordered {

private int order = Ordered.LOWEST_PRECEDENCE;

public void setOrder(int order) {
this.order = order;
}

@Override
public int getOrder() {
return order;
}

@Override
public boolean supports(Object handler) {
return handler instanceof SentinelApiHandler;
}

@Override
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
SentinelApiHandler sentinelApiHandler = (SentinelApiHandler)handler;
sentinelApiHandler.handle(request, response);
return null;
}

@Override
public long getLastModified(HttpServletRequest request, Object handler) {
return -1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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
*
* http://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.csp.sentinel.transport.command;

import com.alibaba.csp.sentinel.command.CommandHandler;
import com.alibaba.csp.sentinel.transport.log.CommandCenterLog;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* @author shenbaoyong
*/
public class SentinelApiHandlerMapping extends AbstractHandlerMapping {

final static Map<String, CommandHandler> handlerMap = new ConcurrentHashMap<>();

private boolean ignoreInterceptor = true;

public SentinelApiHandlerMapping() {
setOrder(Ordered.LOWEST_PRECEDENCE - 10);
}

@Override
protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
String commandName = request.getRequestURI();
if(commandName.startsWith("/")){
commandName = commandName.substring(1);
}
CommandHandler commandHandler = handlerMap.get(commandName);
return commandHandler != null ? new SentinelApiHandler(commandHandler) : null;
}

@Override
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {
return ignoreInterceptor ? new HandlerExecutionChain(handler) : super.getHandlerExecutionChain(handler, request);
}

public void setIgnoreInterceptor(boolean ignoreInterceptor) {
this.ignoreInterceptor = ignoreInterceptor;
}

public static void registerCommand(String commandName, CommandHandler handler) {
if (StringUtil.isEmpty(commandName) || handler == null) {
return;
}

if (handlerMap.containsKey(commandName)) {
CommandCenterLog.warn("[SentinelApiHandlerMapping] Register failed (duplicate command): " + commandName);
return;
}

handlerMap.put(commandName, handler);
}

public static void registerCommands(Map<String, CommandHandler> handlerMap) {
if (handlerMap != null) {
for (Map.Entry<String, CommandHandler> e : handlerMap.entrySet()) {
registerCommand(e.getKey(), e.getValue());
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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
*
* http://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.csp.sentinel.transport.command;

import com.alibaba.csp.sentinel.command.CommandHandler;
import com.alibaba.csp.sentinel.command.CommandHandlerProvider;
import com.alibaba.csp.sentinel.spi.SpiOrder;
import com.alibaba.csp.sentinel.transport.CommandCenter;

import java.util.Map;

/**
* @author shenbaoyong
*/
@SpiOrder(SpiOrder.LOWEST_PRECEDENCE - 100)
public class SpringMvcHttpCommandCenter implements CommandCenter {

@Override
public void start() throws Exception {

}

@Override
public void stop() throws Exception {

}

@Override
public void beforeStart() throws Exception {
// Register handlers
Map<String, CommandHandler> handlers = CommandHandlerProvider.getInstance().namedHandlers();
SentinelApiHandlerMapping.registerCommands(handlers);
}
}
Loading