自己动手写一个服务网关-java
自己动手写一个服务网关
原文链接:https://www.cnblogs.com/bigben0123/p/9252444.html
引言
什么是网关?为什么需要使用网关?
如图所示,在不使用网关的情况下,我们的服务是直接暴露给服务调用方。当调用方增多,势必需要添加定制化访问权限、校验等逻辑。当添加API网关后,再第三方调用端和服务提供方之间就创建了一面墙,这面墙直接与调用方通信进行权限控制。
本文所实现的网关源码抄袭了---Oh,不对,是借鉴。借鉴了Zuul网关的源码,提炼出其核心思路,实现了一套简单的网关源码,博主将其改名为Eatuul。
题外话
本文是业内能搜到的第一篇自己动手实现网关的文章。博主写的手把手系列的文章,目的是在以最简单的方式,揭露出中间件的核心原理,让读者能够迅速了解实现的核心。需要说明的是,这不是源码分析系列的文章,因此写出来的代码,省去了一些复杂的内容,毕竟大家能理解到该中间件的核心原理即可。如果想看源码分析系列的,请关注博主,后期会将spring、spring boot、dubbo、mybatis等开源框架一一揭示。
正文
设计思路
先大致说一下,就是定义一个Servlet接收请求。然后经过preFilter(封装请求参数),routeFilter(转发请求),postFilter(输出内容)。三个过滤器之间,共享request、response以及其他的一些全局变量。如下图所示
和真正的Zuul的区别?
主要区别有如下几点
(1)Zuul中在异常处理模块,有一个ErrorFilter来处理,博主在实现的时候偷懒了,略去。
(2)Zuul中PreFilters,RoutingFilters,PostFilters默认都实现了一组,具体如下表所示:
博主总不可能每一个都给你们实现一遍吧。所以偷懒了,每种只实现一个。但是调用顺序还是不变,按照PreFilters->RoutingFilters->PostFilters的顺序调用。
(3)在routeFilters确实有转发请求的Filter,然而博主偷天换日了,改用RestTemplate实现。
代码结构
大家去spring官网上搭建一套springboot的项目,博主就不展示pom的代码了。直接将项目结构展示一下,如下图所示
EatuulServlet.java
这个是网关的入口,逻辑也十分简单,分为三步
(1)将request,response放入threadlocal中
(2)执行三组过滤器
(3)清除threadlocal中的的环境变量
源码如下
package com.rjzheng.eatuul.http;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "eatuul", urlPatterns = "/*")
public class EatuulServlet extends HttpServlet {
private EatRunner eatRunner = new EatRunner();
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//将request,和response放入上下文对象中
eatRunner.init(req, resp);
try { //执行前置过滤
eatRunner.preRoute(); //执行过滤
eatRunner.route(); //执行后置过滤
eatRunner.postRoute();
} catch (Throwable e) {
RequestContext.getCurrentContext().getResponse()
.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
} finally {
//清除变量
RequestContext.getCurrentContext().unset();
}
}
}
EatuulRunner.java
这个是具体的执行器。需要说明一下,在Zuul中,ZuulRunner在获取具体有哪些过滤器的时候,有一个FileLoader可以动态读取配置加载。博主在实现我们自己的EatuulRunner时候,略去动态读取的过程,直接静态写死。
源码如下
package com.rjzheng.eatuul.http;
import java.util.ArrayList;import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.rjzheng.eatuul.filter.EatuulFilter;
import com.rjzheng.eatuul.filter.post.SendResponseFilter;
import com.rjzheng.eatuul.filter.pre.RequestWrapperFilter;
import com.rjzheng.eatuul.filter.route.RoutingFilter;
public class EatRunner {
//静态写死过滤器
private ConcurrentHashMap<String, List<EatuulFilter>> hashFiltersByType = new ConcurrentHashMap<String, List<EatuulFilter>>(){{
put("pre",new ArrayList<EatuulFilter>(){{
add(new RequestWrapperFilter());
}});
put("route",new ArrayList<EatuulFilter>(){{
add(new RoutingFilter());
}});
put("post",new ArrayList<EatuulFilter>(){{
add(new SendResponseFilter());
}});
}};
public void init(HttpServletRequest req, HttpServletResponse resp) {
RequestContext ctx = RequestContext.getCurrentContext();
ctx.setRequest(req);
ctx.setResponse(resp);
} public void preRoute() throws Throwable {
runFilters("pre");
} public void route() throws Throwable{
runFilters("route");
} public void postRoute() throws Throwable{
runFilters("post");
}
public void runFilters(String sType) throws Throwable {
List<EatuulFilter> list = this.hashFiltersByType.get(sType); if (list != null) {
for (int i = 0; i < list.size(); i++) {
EatuulFilter zuulFilter = list.get(i);
zuulFilter.run();
}
}
}
}
EatuulFilter.java
接下来就是一系列Filter的代码了,先上父类EatuulFilter的源码
package com.rjzheng.eatuul.filter;
public abstract class EatuulFilter {
abstract public String filterType();
abstract public int filterOrder();
abstract public void run();
}
RequestWrapperFilter.java
这个是PreFilter,前置执行过滤器,负责封装请求。步骤如下所示
(1)封装请求头
(2)封装请求体
(3)构造出RestTemplate能识别的RequestEntity
(4)将RequestEntity放入全局threadlocal之中
代码如下所示
package com.rjzheng.eatuul.filter.pre;
import java.io.IOException;import java.io.InputStream;
import java.net.URI;import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import com.rjzheng.eatuul.filter.EatuulFilter;
import com.rjzheng.eatuul.http.RequestContext;
public class RequestWrapperFilter extends EatuulFilter{
@Override
public String filterType() {
// TODO Auto-generated method stub
return "pre";
}
@Override
public int filterOrder() {
// TODO Auto-generated method stub
return -1;
}
@Override
public void run() {
String rootURL = "http://localhost:9090";
RequestContext ctx =RequestContext.getCurrentContext();
HttpServletRequest servletRequest = ctx.getRequest();
String targetURL = rootURL + servletRequest.getRequestURI();
RequestEntity<byte[]> requestEntity = null; try {
requestEntity = createRequestEntity(servletRequest, targetURL);
} catch (Exception e) {
e.printStackTrace();
} //4、将requestEntity放入全局threadlocal之中
ctx.setRequestEntity(requestEntity);
}
private RequestEntity createRequestEntity(HttpServletRequest request,String url) throws URISyntaxException, IOException {
String method = request.getMethod();
HttpMethod httpMethod = HttpMethod.resolve(method); //1、封装请求头
MultiValueMap<String, String> headers =createRequestHeaders(request); //2、封装请求体
byte[] body = createRequestBody(request); //3、构造出RestTemplate能识别的RequestEntity
RequestEntity requestEntity = new RequestEntity<byte[]>(body,headers,httpMethod, new URI(url)); return requestEntity;
}
private byte[] createRequestBody(HttpServletRequest request) throws IOException {
InputStream inputStream = request.getInputStream(); return StreamUtils.copyToByteArray(inputStream);
}
private MultiValueMap<String, String> createRequestHeaders(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
List<String> headerNames = Collections.list(request.getHeaderNames());
for(String headerName:headerNames) {
List<String> headerValues = Collections.list(request.getHeaders(headerName));
for(String headerValue:headerValues) {
headers.add(headerName, headerValue);
}
}
return headers;
}
}
RoutingFilter.java
这个是routeFilter,这里我偷懒了,直接做转发请求,并且将返回值ResponseEntity放入全局threadlocal中
package com.rjzheng.eatuul.filter.route;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.rjzheng.eatuul.filter.EatuulFilter;
import com.rjzheng.eatuul.http.RequestContext;
public class RoutingFilter extends EatuulFilter{ @Override
public String filterType() {
// TODO Auto-generated method stub
return "route";
} @Override
public int filterOrder() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void run(){
RequestContext ctx = RequestContext.getCurrentContext();
RequestEntity requestEntity = ctx.getRequestEntity();
RestTemplate restTemplate = new RestTemplate();
ResponseEntity responseEntity = restTemplate.exchange(requestEntity,byte[].class);
ctx.setResponseEntity(responseEntity);
}
}
SendResponseFilter.java
这个是postFilters,将ResponseEntity输出即可
package com.rjzheng.eatuul.filter.post;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import com.rjzheng.eatuul.filter.EatuulFilter;
import com.rjzheng.eatuul.http.RequestContext;
public class SendResponseFilter extends EatuulFilter{
@Override
public String filterType() {
return "post";
}
@Override
public int filterOrder() {
return 1000;
}
@Override
public void run() {
try {
addResponseHeaders();
writeResponse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void addResponseHeaders() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletResponse servletResponse = ctx.getResponse();
ResponseEntity responseEntity = ctx.getResponseEntity();
HttpHeaders httpHeaders = responseEntity.getHeaders();
for(Map.Entry<String, List<String>> entry:httpHeaders.entrySet()){
String headerName = entry.getKey();
List<String> headerValues = entry.getValue(); for(String headerValue:headerValues) {
servletResponse.addHeader(headerName, headerValue);
}
}
}
private void writeResponse()throws Exception {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletResponse servletResponse = ctx.getResponse();
if (servletResponse.getCharacterEncoding() == null) {
// only set if not set
servletResponse.setCharacterEncoding("UTF-8");
}
ResponseEntity responseEntity = ctx.getResponseEntity();
if(responseEntity.hasBody()) {
byte[] body = (byte[]) responseEntity.getBody();
ServletOutputStream outputStream = servletResponse.getOutputStream();
outputStream.write(body);
outputStream.flush();
}
}
}
RequestContext.java
最后是一直在说的全局threadlocal变量
package com.rjzheng.eatuul.http;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
public class RequestContext extends ConcurrentHashMap<String, Object> { protected static Class<? extends RequestContext> contextClass = RequestContext.class;
protected static final ThreadLocal<? extends RequestContext> threadLocal = new ThreadLocal<RequestContext>() {
@Override
protected RequestContext initialValue() {
try {
return contextClass.newInstance();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
};
public static RequestContext getCurrentContext() {
RequestContext context = threadLocal.get();
return context;
}
public HttpServletRequest getRequest() {
return (HttpServletRequest) get("request");
}
public void setRequest(HttpServletRequest request) {
put("request", request);
}
public HttpServletResponse getResponse() {
return (HttpServletResponse) get("response");
}
public void setResponse(HttpServletResponse response) {
set("response", response);
}
public void setRequestEntity(RequestEntity requestEntity){
set("requestEntity",requestEntity);
}
public RequestEntity getRequestEntity() {
return (RequestEntity) get("requestEntity");
}
public void setResponseEntity(ResponseEntity responseEntity){
set("responseEntity",responseEntity);
}
public ResponseEntity getResponseEntity() {
return (ResponseEntity) get("responseEntity");
}
public void set(String key, Object value) {
if (value != null)
put(key, value);
else
remove(key);
}
public void unset() {
threadLocal.remove();
}
}
如何测试?
自己另外起一个server端口为9090如下所示
package com.rjzheng.eatservice;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import com.rjzheng.eatservice.controller.IndexController;
@SpringBootApplication@ServletComponentScan(basePackageClasses = IndexController.class)
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).
properties("server.port=9090").run(args);
}
}
再来一个controller
package com.rjzheng.eatservice.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@RequestMapping("/index")
public String index() {
return "hello!world";
}
}
然后,你就发现可以从localhost:8080/index进行跳转访问了。
引言
什么是网关?为什么需要使用网关?
如图所示,在不使用网关的情况下,我们的服务是直接暴露给服务调用方。当调用方增多,势必需要添加定制化访问权限、校验等逻辑。当添加API网关后,再第三方调用端和服务提供方之间就创建了一面墙,这面墙直接与调用方通信进行权限控制。
本文所实现的网关源码抄袭了---Oh,不对,是借鉴。借鉴了Zuul网关的源码,提炼出其核心思路,实现了一套简单的网关源码,博主将其改名为Eatuul。
题外话
本文是业内能搜到的第一篇自己动手实现网关的文章。博主写的手把手系列的文章,目的是在以最简单的方式,揭露出中间件的核心原理,让读者能够迅速了解实现的核心。需要说明的是,这不是源码分析系列的文章,因此写出来的代码,省去了一些复杂的内容,毕竟大家能理解到该中间件的核心原理即可。如果想看源码分析系列的,请关注博主,后期会将spring、spring boot、dubbo、mybatis等开源框架一一揭示。
正文
设计思路
先大致说一下,就是定义一个Servlet接收请求。然后经过preFilter(封装请求参数),routeFilter(转发请求),postFilter(输出内容)。三个过滤器之间,共享request、response以及其他的一些全局变量。如下图所示
和真正的Zuul的区别?
主要区别有如下几点
(1)Zuul中在异常处理模块,有一个ErrorFilter来处理,博主在实现的时候偷懒了,略去。
(2)Zuul中PreFilters,RoutingFilters,PostFilters默认都实现了一组,具体如下表所示:
博主总不可能每一个都给你们实现一遍吧。所以偷懒了,每种只实现一个。但是调用顺序还是不变,按照PreFilters->RoutingFilters->PostFilters的顺序调用。
(3)在routeFilters确实有转发请求的Filter,然而博主偷天换日了,改用RestTemplate实现。
代码结构
大家去spring官网上搭建一套springboot的项目,博主就不展示pom的代码了。直接将项目结构展示一下,如下图所示
EatuulServlet.java
这个是网关的入口,逻辑也十分简单,分为三步
(1)将request,response放入threadlocal中
(2)执行三组过滤器
(3)清除threadlocal中的的环境变量
源码如下
package com.rjzheng.eatuul.http;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "eatuul", urlPatterns = "/*")
public class EatuulServlet extends HttpServlet {
private EatRunner eatRunner = new EatRunner();
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//将request,和response放入上下文对象中
eatRunner.init(req, resp);
try { //执行前置过滤
eatRunner.preRoute(); //执行过滤
eatRunner.route(); //执行后置过滤
eatRunner.postRoute();
} catch (Throwable e) {
RequestContext.getCurrentContext().getResponse()
.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
} finally {
//清除变量
RequestContext.getCurrentContext().unset();
}
}
}
EatuulRunner.java
这个是具体的执行器。需要说明一下,在Zuul中,ZuulRunner在获取具体有哪些过滤器的时候,有一个FileLoader可以动态读取配置加载。博主在实现我们自己的EatuulRunner时候,略去动态读取的过程,直接静态写死。
源码如下
package com.rjzheng.eatuul.http;
import java.util.ArrayList;import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.rjzheng.eatuul.filter.EatuulFilter;
import com.rjzheng.eatuul.filter.post.SendResponseFilter;
import com.rjzheng.eatuul.filter.pre.RequestWrapperFilter;
import com.rjzheng.eatuul.filter.route.RoutingFilter;
public class EatRunner {
//静态写死过滤器
private ConcurrentHashMap<String, List<EatuulFilter>> hashFiltersByType = new ConcurrentHashMap<String, List<EatuulFilter>>(){{
put("pre",new ArrayList<EatuulFilter>(){{
add(new RequestWrapperFilter());
}});
put("route",new ArrayList<EatuulFilter>(){{
add(new RoutingFilter());
}});
put("post",new ArrayList<EatuulFilter>(){{
add(new SendResponseFilter());
}});
}};
public void init(HttpServletRequest req, HttpServletResponse resp) {
RequestContext ctx = RequestContext.getCurrentContext();
ctx.setRequest(req);
ctx.setResponse(resp);
} public void preRoute() throws Throwable {
runFilters("pre");
} public void route() throws Throwable{
runFilters("route");
} public void postRoute() throws Throwable{
runFilters("post");
}
public void runFilters(String sType) throws Throwable {
List<EatuulFilter> list = this.hashFiltersByType.get(sType); if (list != null) {
for (int i = 0; i < list.size(); i++) {
EatuulFilter zuulFilter = list.get(i);
zuulFilter.run();
}
}
}
}
EatuulFilter.java
接下来就是一系列Filter的代码了,先上父类EatuulFilter的源码
package com.rjzheng.eatuul.filter;
public abstract class EatuulFilter {
abstract public String filterType();
abstract public int filterOrder();
abstract public void run();
}
RequestWrapperFilter.java
这个是PreFilter,前置执行过滤器,负责封装请求。步骤如下所示
(1)封装请求头
(2)封装请求体
(3)构造出RestTemplate能识别的RequestEntity
(4)将RequestEntity放入全局threadlocal之中
代码如下所示
package com.rjzheng.eatuul.filter.pre;
import java.io.IOException;import java.io.InputStream;
import java.net.URI;import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import com.rjzheng.eatuul.filter.EatuulFilter;
import com.rjzheng.eatuul.http.RequestContext;
public class RequestWrapperFilter extends EatuulFilter{
@Override
public String filterType() {
// TODO Auto-generated method stub
return "pre";
}
@Override
public int filterOrder() {
// TODO Auto-generated method stub
return -1;
}
@Override
public void run() {
String rootURL = "http://localhost:9090";
RequestContext ctx =RequestContext.getCurrentContext();
HttpServletRequest servletRequest = ctx.getRequest();
String targetURL = rootURL + servletRequest.getRequestURI();
RequestEntity<byte[]> requestEntity = null; try {
requestEntity = createRequestEntity(servletRequest, targetURL);
} catch (Exception e) {
e.printStackTrace();
} //4、将requestEntity放入全局threadlocal之中
ctx.setRequestEntity(requestEntity);
}
private RequestEntity createRequestEntity(HttpServletRequest request,String url) throws URISyntaxException, IOException {
String method = request.getMethod();
HttpMethod httpMethod = HttpMethod.resolve(method); //1、封装请求头
MultiValueMap<String, String> headers =createRequestHeaders(request); //2、封装请求体
byte[] body = createRequestBody(request); //3、构造出RestTemplate能识别的RequestEntity
RequestEntity requestEntity = new RequestEntity<byte[]>(body,headers,httpMethod, new URI(url)); return requestEntity;
}
private byte[] createRequestBody(HttpServletRequest request) throws IOException {
InputStream inputStream = request.getInputStream(); return StreamUtils.copyToByteArray(inputStream);
}
private MultiValueMap<String, String> createRequestHeaders(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
List<String> headerNames = Collections.list(request.getHeaderNames());
for(String headerName:headerNames) {
List<String> headerValues = Collections.list(request.getHeaders(headerName));
for(String headerValue:headerValues) {
headers.add(headerName, headerValue);
}
}
return headers;
}
}
RoutingFilter.java
这个是routeFilter,这里我偷懒了,直接做转发请求,并且将返回值ResponseEntity放入全局threadlocal中
package com.rjzheng.eatuul.filter.route;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.rjzheng.eatuul.filter.EatuulFilter;
import com.rjzheng.eatuul.http.RequestContext;
public class RoutingFilter extends EatuulFilter{ @Override
public String filterType() {
// TODO Auto-generated method stub
return "route";
} @Override
public int filterOrder() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void run(){
RequestContext ctx = RequestContext.getCurrentContext();
RequestEntity requestEntity = ctx.getRequestEntity();
RestTemplate restTemplate = new RestTemplate();
ResponseEntity responseEntity = restTemplate.exchange(requestEntity,byte[].class);
ctx.setResponseEntity(responseEntity);
}
}
SendResponseFilter.java
这个是postFilters,将ResponseEntity输出即可
package com.rjzheng.eatuul.filter.post;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import com.rjzheng.eatuul.filter.EatuulFilter;
import com.rjzheng.eatuul.http.RequestContext;
public class SendResponseFilter extends EatuulFilter{
@Override
public String filterType() {
return "post";
}
@Override
public int filterOrder() {
return 1000;
}
@Override
public void run() {
try {
addResponseHeaders();
writeResponse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void addResponseHeaders() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletResponse servletResponse = ctx.getResponse();
ResponseEntity responseEntity = ctx.getResponseEntity();
HttpHeaders httpHeaders = responseEntity.getHeaders();
for(Map.Entry<String, List<String>> entry:httpHeaders.entrySet()){
String headerName = entry.getKey();
List<String> headerValues = entry.getValue(); for(String headerValue:headerValues) {
servletResponse.addHeader(headerName, headerValue);
}
}
}
private void writeResponse()throws Exception {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletResponse servletResponse = ctx.getResponse();
if (servletResponse.getCharacterEncoding() == null) {
// only set if not set
servletResponse.setCharacterEncoding("UTF-8");
}
ResponseEntity responseEntity = ctx.getResponseEntity();
if(responseEntity.hasBody()) {
byte[] body = (byte[]) responseEntity.getBody();
ServletOutputStream outputStream = servletResponse.getOutputStream();
outputStream.write(body);
outputStream.flush();
}
}
}
RequestContext.java
最后是一直在说的全局threadlocal变量
package com.rjzheng.eatuul.http;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
public class RequestContext extends ConcurrentHashMap<String, Object> { protected static Class<? extends RequestContext> contextClass = RequestContext.class;
protected static final ThreadLocal<? extends RequestContext> threadLocal = new ThreadLocal<RequestContext>() {
@Override
protected RequestContext initialValue() {
try {
return contextClass.newInstance();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
};
public static RequestContext getCurrentContext() {
RequestContext context = threadLocal.get();
return context;
}
public HttpServletRequest getRequest() {
return (HttpServletRequest) get("request");
}
public void setRequest(HttpServletRequest request) {
put("request", request);
}
public HttpServletResponse getResponse() {
return (HttpServletResponse) get("response");
}
public void setResponse(HttpServletResponse response) {
set("response", response);
}
public void setRequestEntity(RequestEntity requestEntity){
set("requestEntity",requestEntity);
}
public RequestEntity getRequestEntity() {
return (RequestEntity) get("requestEntity");
}
public void setResponseEntity(ResponseEntity responseEntity){
set("responseEntity",responseEntity);
}
public ResponseEntity getResponseEntity() {
return (ResponseEntity) get("responseEntity");
}
public void set(String key, Object value) {
if (value != null)
put(key, value);
else
remove(key);
}
public void unset() {
threadLocal.remove();
}
}
如何测试?
自己另外起一个server端口为9090如下所示
package com.rjzheng.eatservice;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import com.rjzheng.eatservice.controller.IndexController;
@SpringBootApplication@ServletComponentScan(basePackageClasses = IndexController.class)
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).
properties("server.port=9090").run(args);
}
}
再来一个controller
package com.rjzheng.eatservice.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@RequestMapping("/index")
public String index() {
return "hello!world";
}
}
然后,你就发现可以从localhost:8080/index进行跳转访问了。
自己动手写一个服务网关-java的更多相关文章
- 死磕 java同步系列之自己动手写一个锁Lock
问题 (1)自己动手写一个锁需要哪些知识? (2)自己动手写一个锁到底有多简单? (3)自己能不能写出来一个完美的锁? 简介 本篇文章的目标一是自己动手写一个锁,这个锁的功能很简单,能进行正常的加锁. ...
- 死磕 java线程系列之自己动手写一个线程池
欢迎关注我的公众号"彤哥读源码",查看更多源码系列文章, 与彤哥一起畅游源码的海洋. (手机横屏看源码更方便) 问题 (1)自己动手写一个线程池需要考虑哪些因素? (2)自己动手写 ...
- 动手写一个简单版的谷歌TPU-矩阵乘法和卷积
谷歌TPU是一个设计良好的矩阵计算加速单元,可以很好的加速神经网络的计算.本系列文章将利用公开的TPU V1相关资料,对其进行一定的简化.推测和修改,来实际编写一个简单版本的谷歌TPU.计划实现到行为 ...
- 动手写一个简单版的谷歌TPU-指令集
系列目录 谷歌TPU概述和简化 基本单元-矩阵乘法阵列 基本单元-归一化和池化(待发布) TPU中的指令集 SimpleTPU实例: (计划中) 拓展 TPU的边界(规划中) 重新审视深度神经网络中的 ...
- 动手写一个简单的Web框架(模板渲染)
动手写一个简单的Web框架(模板渲染) 在百度上搜索jinja2,显示的大部分内容都是jinja2的渲染语法,这个不是Web框架需要做的事,最终,居然在Werkzeug的官方文档里找到模板渲染的代码. ...
- 动手写一个简单的Web框架(Werkzeug路由问题)
动手写一个简单的Web框架(Werkzeug路由问题) 继承上一篇博客,实现了HelloWorld,但是这并不是一个Web框架,只是自己手写的一个程序,别人是无法通过自己定义路由和返回文本,来使用的, ...
- 动手写一个简单的Web框架(HelloWorld的实现)
动手写一个简单的Web框架(HelloWorld的实现) 关于python的wsgi问题可以看这篇博客 我就不具体阐述了,简单来说,wsgi标准需要我们提供一个可以被调用的python程序,可以实函数 ...
- 死磕 java线程系列之自己动手写一个线程池(续)
(手机横屏看源码更方便) 问题 (1)自己动手写的线程池如何支持带返回值的任务呢? (2)如果任务执行的过程中抛出异常了该怎么处理呢? 简介 上一章我们自己动手写了一个线程池,但是它是不支持带返回值的 ...
- java单链表的实现自己动手写一个单链表
单链表:单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素.链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置),元素就是 ...
随机推荐
- kindeditor实现ctrl+v粘贴word图片并上传
Chrome+IE默认支持粘贴剪切板中的图片,但是我要发布的文章存在word里面,图片多达数十张,我总不能一张一张复制吧?Chrome高版本提供了可以将单张图片转换在BASE64字符串的功能.但是无法 ...
- DP(第二版)
第一版请见:直通 话不多说,直接上题 1.P1040 加分二叉树 直通 思路: 已知中序遍历,相当于一段区间了,所以我们枚举一个k,如果以k为根节点,能够将分数更新,那么这段区间的根节点就置为k,最后 ...
- 「CF716D」Complete The Graph「最短路」
题意 给定一个\(n\)个点\(m\)条边的无向图,有一些边权暂时为\(0\),你需要分配一个\([1, 10^{18}]\)的数.最终使得\(s\)到\(t\)最短路为\(L\),输出一个可行的分配 ...
- 8月清北学堂培训 Day 7
当天走得太兴奋了,忘记保存就关电脑了o(╥﹏╥)o,现在补上( p′︵‵.) 今天是杨思祺老师的讲授~ 练习题 首先求出最短路: 如果选择的边不是最短路上的边,那么毫无影响: 对于最短路径上的边,我们 ...
- P3469 割点的应用
https://www.luogu.org/problem/P3469 题目就是说封锁一个点,会导致哪些点(对)连不通: 用tarjan求割点,如果这个点是割点,那么不能通行的点对数就是(乘法法则)儿 ...
- codeforces gym #101161E - ACM Tax(lca+主席树)
题目链接: http://codeforces.com/gym/101161/attachments 题意: 给出节点数为$n$的树 有$q$次询问,输出$a$节点到$b$节点路程中,经过的边的中位数 ...
- Django module
1,模型定义 models.py的例子: class Author(models.Model): name=models.CharField(max_length=20) class Book(mod ...
- 阶段5 3.微服务项目【学成在线】_day03 CMS页面管理开发_01-自定义查询页面-服务端-Dao
在页面输入查询条件,查询符合条件的页面信息. 查询条件如下: 站点Id:精确匹配 模板Id:精确匹配 页面别名:模糊匹配 spring mongoDB如何自定义条件 在Repository的findA ...
- 加载selenium库
一.maven的下载.解压以及环境变量配置 1.下载maven: 官网下载地址:http://maven.apache.org/download.cgi 在Files下面下载对应的maven版本(官网 ...
- centos安装tidy扩展
wget http://pecl.php.net/get/tidy-1.2.tgztar -xvzf tidy-1.2.tgzcd tidy-1.2/usr/local/php/bin/phpize. ...