当前位置: 首页 > 知识库问答 >
问题:

如何在spring boot 1.3.x中为嵌入式tomcat添加tomcat会话复制

李锦
2023-03-14
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import in.megacabs.web.filter.CachingHttpHeadersFilter;
import in.megacabs.web.filter.StaticResourcesProductionFilter;
import in.megacabs.web.rest.filter.megacabs.ServerModifiedFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.*;
import javax.inject.Inject;
import javax.servlet.*;

/**
 * Configuration of web application with Servlet 3.0 APIs.
 */
@Configuration
@AutoConfigureAfter(CacheConfiguration.class)
public class WebConfigurer extends WebMvcConfigurerAdapter implements ServletContextInitializer, EmbeddedServletContainerCustomizer {

    private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);

    @Inject
    private Environment env;

    @Inject
    private JHipsterProperties props;

    @Autowired(required = false)
    private MetricRegistry metricRegistry;

    @Inject
    private JasperReportConfiguration reportConfiguration;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
        registry.addResourceHandler(reportConfiguration.getUploadUrl()+"*//**").addResourceLocations("file://"+ reportConfiguration.getUploadPath()+"/");
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles()));
        EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
        if (!env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
            initMetrics(servletContext, disps);
        }
        if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) {
            initCachingHttpHeadersFilter(servletContext, disps);
            initStaticResourcesProductionFilter(servletContext, disps);
        }
        initServerModifiedFilter(servletContext, disps);

        log.info("Web application fully configured");
    }

    /**
     * Set up Mime types.
     */
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        // IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
        mappings.add("html", "text/html;charset=utf-8");
        // CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
        mappings.add("json", "text/html;charset=utf-8");
        container.setMimeMappings(mappings);
    }

    /**
     * Initializes the static resources production Filter.
     */
    private void initStaticResourcesProductionFilter(ServletContext servletContext,
                                                     EnumSet<DispatcherType> disps) {

        log.debug("Registering static resources production Filter");
        FilterRegistration.Dynamic staticResourcesProductionFilter =
            servletContext.addFilter("staticResourcesProductionFilter",
                new StaticResourcesProductionFilter());

        staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/");
        staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html");
        staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/assets/*");
        staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
        staticResourcesProductionFilter.setAsyncSupported(true);
    }

    /**
     * Initializes the caching HTTP Headers Filter.
     */
    private void initCachingHttpHeadersFilter(ServletContext servletContext,
                                              EnumSet<DispatcherType> disps) {
        log.debug("Registering Caching HTTP Headers Filter");
        FilterRegistration.Dynamic cachingHttpHeadersFilter =
            servletContext.addFilter("cachingHttpHeadersFilter",
                new CachingHttpHeadersFilter(env));

        cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/dist/assets/*");
        cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/dist/scripts/*");
        cachingHttpHeadersFilter.setAsyncSupported(true);
    }

    /**
     * Initializes Metrics.
     */
    private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
        log.debug("Initializing Metrics registries");
        servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE,
            metricRegistry);
        servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY,
            metricRegistry);

        log.debug("Registering Metrics Filter");
        FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter",
            new InstrumentedFilter());

        metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
        metricsFilter.setAsyncSupported(true);

        log.debug("Registering Metrics Servlet");
        ServletRegistration.Dynamic metricsAdminServlet =
            servletContext.addServlet("metricsServlet", new MetricsServlet());

        metricsAdminServlet.addMapping("/metrics/metrics/*");
        metricsAdminServlet.setAsyncSupported(true);
        metricsAdminServlet.setLoadOnStartup(2);
    }

    /**
     * Initializes the serverModified Filter.
     */
    private void initServerModifiedFilter(ServletContext servletContext,
                                          EnumSet<DispatcherType> disps) {
        log.debug("Registering static resources production Filter");
        FilterRegistration.Dynamic serverModifiedFilter =
            servletContext.addFilter("serverModifiedFilter",
                new ServerModifiedFilter());

        serverModifiedFilter.addMappingForUrlPatterns(disps, true, "/api/*");
        serverModifiedFilter.setAsyncSupported(true);
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = props.getCors();
        if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
            source.registerCorsConfiguration("/api/**", config);
            source.registerCorsConfiguration("/v2/api-docs", config);
            source.registerCorsConfiguration("/oauth/**", config);
        }
        return new CorsFilter(source);
    }

}

请帮助我,如果有人设置tomcat会话复制之前。

共有1个答案

吕征
2023-03-14

我们使用Hazelcast在企业应用程序中进行会话复制/集群。

您需要将相关的依赖项添加到build.gradle文件中:

dependencies {
    //Main dependencies
    compile 
        'com.hazelcast:hazelcast:3.3.5',
        'com.hazelcast:hazelcast-wm:3.3.5',
        'com.hazelcast:hazelcast-spring:3.3.5'
}

然后我们创建一个Hazelcast配置类:

import com.hazelcast.config.Config
import com.hazelcast.config.JoinConfig
import com.hazelcast.config.MulticastConfig
import com.hazelcast.config.NetworkConfig
import com.hazelcast.core.Hazelcast
import com.hazelcast.core.HazelcastInstance
import com.hazelcast.web.SessionListener
import com.hazelcast.web.WebFilter
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.embedded.FilterRegistrationBean
import org.springframework.boot.context.embedded.ServletListenerRegistrationBean
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn

import javax.servlet.DispatcherType

@Configuration
@ConfigurationProperties(prefix="hzl")
@ConditionalOnProperty(value= "hzl.enabled")
class HazelcastConfig {
    String address
    Integer port
    Integer multicastPort
    String instanceName
    Integer multicastTimeoutSeconds

    @Bean
    public hazelcastInstance(){
        Config config = new Config()
        config.instanceName = instanceName

        config.setProperty("hazelcast.jmx", "true")

        NetworkConfig network = config.networkConfig
        network.port = port ?: network.port

        JoinConfig join = network.join
        join.tcpIpConfig.enabled = false
        join.awsConfig.enabled = false

        MulticastConfig multicastConfig = join.multicastConfig
        multicastConfig.enabled = true
        multicastConfig.multicastGroup = address

        multicastConfig.multicastPort = multicastPort ?: multicastConfig.multicastPort
        multicastConfig.multicastTimeoutSeconds = multicastTimeoutSeconds ?: multicastConfig.multicastTimeoutSeconds

        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config)
        instance
    }

    @Bean
    @DependsOn(["hazelcastInstance"])
    public FilterRegistrationBean hazelcastFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean()
        WebFilter filter = new WebFilter()

        registration.filter = filter
        registration.order = 0
        registration.name = "hazelcastFilter"
        registration.addUrlPatterns("/*")
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE)

        registration.addInitParameter("instance-name", instanceName)
//        registration.addInitParameter("session-ttl-seconds", "3600")
        registration.addInitParameter("sticky-session", "false")
        registration.addInitParameter("deferred-write", "false")
        registration.addInitParameter("sticky-session", "true")

        registration
    }

    @Bean
    public ServletListenerRegistrationBean hazelcastSessionListener() {
        return new ServletListenerRegistrationBean(new SessionListener());
    }
}
#Hazelcast Session Replication
hzl.enabled=true
hzl.address=224.2.2.110
hzl.multicastTimeoutSeconds=60
 类似资料:
  • 我有时会在pom中看到以下声明。xml。。。 如您所见,sping-boo-starter-web被声明为tomcat-embed-jasper。 是不是sping-boo-starter-web已经有一个嵌入式tomcat了?为什么一些开发人员仍然声明tomcat-embed-jasper以及boot-starter-web?还是有什么原因?

  • 在我们的项目中,当将另一个现有war文件添加到Grails/Spring Boot中的嵌入式tomcat容器时,我们的默认Hibernate会话似乎丢失了。 我们使用的是在Spring boot上构建的Grails3.3.1,并通过applications.groovy文件以这种方式将现有的war文件添加到emnbedded tomcat中。 当设置了上述内容后,应用程序和外部war文件都将启动,

  • 我已经搜索了这个问题,但我没有找到任何关于这个案例的东西。我发现了很多“如何将Spring Boot WAR部署到Tomcat”,但是没有关于用Spring Boot包装现有的Tomcat WAR的内容。 我正在尝试用Spring Boot“包装器”包装一个现有的WAR,这样就不必重新配置现有的代码库。这个解决方案不起作用,因为它依赖于在绝对位置可用的WAR,而我们正试图将“应用程序”WAR打包在

  • 基本上,我想在Tomcat 8嵌入式中运行一些Rest类。我不确定如何将它们添加到我正在创建的tomcat嵌入式实例中。所以这就是我所做的。这里只有泽西班: 下面是我创建Tomcat的类: 正如你看到的,带问号的部分给我制造麻烦。还有一个lats问题,这就是我应该添加这些类以在服务器上运行的方式,对吗? 更新我添加了Michal Gajdos建议的行,但在启动时我得到: 线程“main”java中

  • 我正在使用NetBeans IDE和带有Spring Boot的Maven。每当我运行我的应用程序不止一次,我就会得到这个错误: O.A.Coyote.http11.http11nioprotocol:无法启动与ProtocolHandler关联的终结点[“http-nio-8080”] spring boot java.lang.IllegalStateException:Tomcat连接器处于

  • 我正在尝试创建一个Spring Boot应用程序,除了当我访问localhost:8080时必须插入用户名和密码外,所有的东西都运行得很好。我不知道如何从我的应用程序向嵌入式tomcat添加一个新的tomcat用户。 这是我的pom XML: 下面是tomcat可见的项目结构: