Friday, February 5, 2016

Does Spring's RestTemplate re-use connections?

This question has come up recently in several conversations with my colleagues: does Spring's RestTemplate re-use connections when making REST requests to the same host?

The answer was not that obvious. Even though we are using RestTemplate for executing REST calls, the actual connections are opened by underlying ClientHttpRequestFactory. By default, RestTemplate is created with SimpleClientHttpRequestFactory, which uses standard Java Library's UrlHttpConnection.

Starting from Java ?, UrlHttpConnection supports HTTP 1.1 and keep-alive, if destination server supports it, if certain conditions are satisfied. You can turn it off or specify the maximum number of open connections via system properties, but those are all the options you have.  For several reasons, there is no option to specify how long  the connection can stay open.

However, we have an option to instantiate RestTemplate with HttpComponentsClientHttpRequestFactory, which uses Apache's HttpComponents library to manage connections. This allows greater control over connection pool settings. 

So, the answer to the question in the title: YES, RestTemplate re-uses connections if certain conditions are met.




Thursday, January 7, 2016

Tutorial: connecting to Cassandra using Spring Boot and spring-data-cassandra.

Starting version 1.3, Spring Boot supports Cassandra auto configuration. That made using spring-cassandra-data even easier.

Prerequisites:
  •    Configured Spring Boot project version 1.3 or higher.
  •    Cassandra instance. On this instance, create a keyspace movies and in it table movie
       Create table movie:

CREATE TABLE movie (
  movieid text,
  name text,
  PRIMARY KEY ((movieid))
)
     and insert a couple of rows:

   insert into movie(movieid, name) values('id1', 'Star Wars');
   insert into movie(movieid, name) values('id2', 'Casablanca');

1. Add spring-data-cassandra dependency for Spring Boot:

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-cassandra</artifactId>
    </dependency>

2. Create a Java Bean with mapping to cassandra table:


@Table
public class Movie {
    @PrimaryKey
    private String movieid;

    @Column
    private String name;
        // add getters, setters, equals, hashCode

}

3.  Create Repository Interface for your bean:

 public interface MovieRepository extends TypedIdCassandraRepository<Movie,String> {
}


4.  Add basic  RestController which can be expanded on later:

@RestController
public class MovieController {
    @Autowired
    MovieRepository movieRepository;

    @RequestMapping(value="/movies")
    public Iterable<Movie> getTable1(){
        return movieRepository.findAll();
    }

}
5.  Update resources/application.properties with Cassandra connection details:

spring.data.cassandra.keyspace-name=...
spring.data.cassandra.contact-points=...
spring.data.cassandra.port=...
6.  Add mappingContext bean to your configuration with the package with mapped beans:


    @Bean
    public CassandraMappingContext mappingContext() throws Exception {
        BasicCassandraMappingContext bean = new BasicCassandraMappingContext();
        bean.setInitialEntitySet(CassandraEntityClassScanner.scan(("yourpackage")));

        return bean;
    }

7. Run your app. You should see the following at localhost:8080/movies:

[
  {
    "movieid": "id1",
    "name": "Star Wars"
  },
  {
    "movieid": "id2",
    "name": "Casablanca"
  }
]

Monday, December 7, 2015

Adding Custom metrics in Spring Boot

spring-boot-actuator makes it easy to add custom metrics to the Spring Boot application. For example, we would like to know, how many times a particular method was executed in a service.
What we would need to do is just autowire CounterService and add the call to counterService in the method:

    @Autowired
    private CounterService counterService;


    ...
    public void sampleMethod() {
        counterService.increment
             ("sampleservice.samplemethod.counter");
        ....

    }

If we start the application and access /metrics endpoint, we should see


 "counter.sampleservice.samplemethod.counter":...,


But what if we want to do something more sofisticated, for example, how many times the method was called in the last 5 minutes. Codahale metrics library gives us that functionality and it is integrated with Spring Boot.

You need to add dependency to your pom.xml:

    <dependency>
            <groupId>com.codahale.metrics</groupId>
            <artifactId>metrics-core</artifactId>
    </dependency> 

Then you autowire  MetricRegistry where you want to use metrics:

    @Autowired
    private MetricRegistry metricRegistry;

Now just register the metrics and start using it:
   private Meter meter;

    @PostConstruct
    public void init() {
        meter=metricRegistry.meter("example");
    }


The metrics will show up in the /metrics endpoint:

  "example.fiveMinuteRate": 0,
  "example.oneMinuteRate": 0,
  "example.count": 0,
  "example.fifteenMinuteRate": 0,

Saturday, November 7, 2015

Cloudy with a chance of confusion

Cloud is very popular these day, one of the consequences is the number of terms and products which have the word Cloud in its name which causes a lot of confusion.
I'll try to collect here some of them.

  • CloudFormation - AWS Configuration management tool, which uses templates with a special format.
  • CloudStack - opensource software to manage VMs.
  • CloudFoundry - cloud computing PaaS, some of the cloud providers (e.g. IBM Bluemix) are based on it

Friday, November 6, 2015

Using Java 8 CompletableFuture with Spring @Async annotated methods

Future interface was added in Java 5 but it had a major downside: you had to wait for it to return the result if you wanted to do something with it. Spring framework added SettableListenableFuture which allowed to register callbacks, but now Java 8 added CompletableFuture class and in release 4.2 Spring added support for it.


CompletableFuture allows to chain several asynchronous calls which takes asynchronous to another level. But the class is rather complex, it has more than 40 methods. How do we take advantage of it together with asynchronous support offered by Spring?
 
Lets say we are implementing a method which returns a String result:
 
 public String getResult() {
     return "result";
}

Now we want to make this method asynchronous and return CompletableFuture. Let's assume we already have all the necessary configurations for executing methods with @Async (i.e. we have @EnableAsync annotation in the configuration and defined TaskExecutor bean).

First, we'll add @Async annotation to the method and change the return type.

@Async
public CompletableFuture<String> getResult() {
     return "result";
}

This will not even compile.  But how do we convert string to CompletableFuture? We can use the static method completedFuture:
 
@Async
public CompletableFuture<String> getResult() {
     return CompletableFuture.completedFuture("result");
}

We also need to process the result in the calling method. If we want to process both successes and failures we can execute whenComplete method:

getResult().whenComplete(...);

Now you've taken advantage of CompletableFuture.

Friday, September 25, 2015

Most useful git commands

My favorites are:

git status

This is my favorite git command line command. Right away you can see the branch you are on, all the files that has been changed, the files which are not staged to commit.

git branch -r 

This command shows all remote branches, so you don't have to remember the name of the feature branch which has a 4-digit JIRA story id.


What are yours?

Wednesday, September 2, 2015

Migrating Spring Rest Service Application to Spring Boot (Part III)

You can read Part I and Part II here and here.

Spring Boot provides a good support for unit and integration testing.  I wanted to take an advantage of that.

First I added dependency for spring-boot-starter-test in my pom.xml,   removed dependencies for jUnit, Mockito and Hamcrest and ran the tests.

Things were not going as smooth as I hoped.

I was using mockMVC which was wired to my WebConfig class (via ContextConfiguration). But that class is no longer needed as Spring Boot takes care of everything. After some digging, adding @SpringApplicationConfiguration(classes = MockApp.class)  worked.

Running unit tests was very useful: it turned out that when removing WebConfig I removed important configuration: useRegisteredSuffixPatternMatch was set to true, which allowed rest requests with domain names in them to be processed correctly and prevented Spring from incorrectly interpreting .com as file extension.

However simply adding this configuration back did not work.  I found several blogs regarding the same issue. In the end the solution was simple, I added back WebConfig which extends WebMvcConfigurerAdapter with overridden configurePathMatch method, but removed @ComponentScan from it.