如今,由于我们在响应中发送大量数据,因此必须对API响应执行Gzip压缩。 它节省了网络带宽和交付时间,当然还节省了Internet上的空间。
CXF提供了以多种方式使用Gzip压缩的选项。
- 蓝图
- 注解
蓝图:
<bean id="gZipInterceptor" class="org.apache.cxf.transport.common.gzip.GZIPOutInterceptor" /><jaxrs:server id="rsServer" address="/gZip"><jaxrs:outInterceptors><ref component-id="gZipInterceptor" /></jaxrs:outInterceptors></jaxrs:server>
注解:
首先,您需要在out拦截器列表中注册GZIPOutInterceptor
。 为此,您需要加入CXF初始化类。
public class InterceptorManager extends AbstractFeature {private static final Logger LOGGER = Logger.getLogger( "simcore" );private static final Interceptor< Message > GZIP = new GZIPOutInterceptor();//private static final Interceptor< Message > GZIP = new GZIPOutInterceptor(512);/* (non-Javadoc)* @see org.apache.cxf.feature.AbstractFeature#initializeProvider(org.apache.cxf.interceptor.InterceptorProvider, org.apache.cxf.Bus)*/@Overrideprotected void initializeProvider( InterceptorProvider provider, Bus bus ) {/*** Adding Gzip interceptor to all outbound requests/responses*/LOGGER.debug( " ############## Adding Gzip as OUT Interceptor ##############" );provider.getOutInterceptors().add( GZIP );}
}
GZIPOutInterceptor
带有一个选项,用于将阈值设置为字节数。 如果响应大小低于此阈值,则将不会对其进行压缩。 当我们仅发送空列表和状态消息/代码时,这将非常有用,因为压缩这些小的响应将在服务器端增加开销。
但是,我们还必须考虑另一个因素,即请求响应的用户数量。 因此,请考虑可能出现的所有情况,以适当地设置此值。
@GZIP
现在,我们可以在任何Web服务控制器上使用此批注,以对该类中提供的所有API实施压缩。
@WebService
@Consumes ( { MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON } )
@Produces ( MediaType.APPLICATION_JSON )
@GZIP
public interface WebServicesController {@GET@Path ( "/myGzipData" )@Produces ( { MediaType.APPLICATION_JSON } )Response getZipData( );}
此外,我们可以在Gzip注释中设置不同的参数。
@GZIP ( force = true, threshold = 512 )
翻译自: https://www.javacodegeeks.com/2014/11/adding-gzip-compression-in-cxf-apis-and-interceptors.html