Using spring cloud, sometimes when we return content to the client, we often need to add some extra things. For example, encryption, adding one more return value, etc. Of course, it can be processed in the method, but if there are many methods and need to be processed uniformly, it is very inconvenient. At this time, it can be processed uniformly through the filter of zuulGateway.
Looking directly at the code, it's very simple:
import java.io.InputStream; import java.nio.charset.Charset; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import org.springframework.util.StreamUtils; import org.springframework.util.StringUtils; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.poly.zuul.common.Constants; import com.poly.zuul.enums.ServiceId; import com.poly.zuul.utils.AESJSEncryptUtils; import com.poly.zuul.utils.RsaEncryptUtil; /** * Return value output filter, used here to process the return value * * @Title: ResponseFilter * @Description: * @author kokJuis * @date 9:52:42 AM */ public class ResponseFilter extends ZuulFilter { @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); try { // Get the content of the return value and process it InputStream stream = context.getResponseDataStream(); String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8")); String returnStr = ""; // your processing logic, encryption, adding new return values, etc... // rewrite the content context.setResponseBody(returnStr); } catch (Exception e) { e.printStackTrace (); } return null; } @Override public boolean shouldFilter() { RequestContext ctx = RequestContext.getCurrentContext(); String requestURI = String.valueOf(ctx.get("requestURI")); if (requestURI.contains(Constants.alipay)) { // URL requests that do not need to be processed, return false return false; } return true; } @Override public int filterOrder() { return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 3; } @Override public String filterType() { return FilterConstants.POST_TYPE;// After the request is processed, it will enter the filter } }
Then register the filter in @Configuration.
@Bean public ResponseFilter responseFilter() { return new ResponseFilter(); }