Count active requests with Spring Boot

By making on Sep 05, 2014

Count active requests with Spring Boot

package hoge;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.*;
import java.io.IOException;

@EnableAutoConfiguration
@ComponentScan
@RestController
public class Application {
    @RequestMapping("/")
    String hoge() throws Exception {
        Thread.sleep(5000);
        return "hoge";
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Configuration
    static class Config {
        @Autowired
        CounterService counterService;

        @Bean
        Filter counterFilter() {
            return new Filter() {
                @Override
                public void init(FilterConfig filterConfig) throws ServletException {
                }

                @Override
                public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                    try {
                        counterService.increment("active-http-sessions");
                        filterChain.doFilter(servletRequest, servletResponse);
                    } finally {
                        counterService.decrement("active-http-sessions");
                    }
                }

                @Override
                public void destroy() {
                }
            };
        }

    }
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.