Tag: Spring

Microservices with Spring

ENGINEERING

Introduction

NOTE: Revised June 2018

A simple example of setting up a microservices system using Spring, Spring Boot and Spring Cloud.

Microservices allow large systems to be built up from a number of collaborating components. It does at the process level what Spring has always done at the component level: loosely coupled processes instead of loosely coupled components.

Shopping ApplicationFor example imagine an online shop with separate microservices for user-accounts, product-catalog order-processing and shopping carts:

Inevitably there are a number of moving parts that you have to setup and configure to build such a system. How to get them working together is not obvious – you need to have good familiarity with Spring Boot since Spring Cloud leverages it heavily, several Netflix or other OSS projects are required and, of course, there is some Spring configuration “magic”!

Demo ApplicationIn this article I aim to clarify how things work by building the simplest possible system step-by-step. Therefore, I will only implement a small part of the big system – the user account service.

The Web-Application will make requests to the Account-Servicemicroservice using a RESTful API. We will also need to add a discovery service – so the other processes can find each other.

The code for this application is here: https://github.com/paulc4/microservices-demo.

The description of how it works is deliberately detailed. Impatient readers may prefer to simply look at the code. Note that it contains three microservices in a single project.

Follow-Up 1: Other Resources

This article only discusses a minimal system. For more information, you might like to read Josh Long’s blog article Microservice Registration and Discovery with Spring Cloud and Netflix’s Eureka which shows running a complete microservice system on Cloud Foundry.

The Spring Cloud projects are here.

Follow Up 2: SpringOne Platform 2018

Book your place at SpringOne2 Platform in Washington DC, USA this September – simply the best opportunity to find out first hand all that’s going on and to provide direct feedback. The name has changed, from Spring One, to reflect the growth of Spring in platform services (such as the Spring Cloud projects).

Updates (June 2018)

A number of changes since I originally wrote this blog:

  1. discussion of using multiple instances of the same service on the same host.. Demo application updated to match.
  2. discussion of @LoadBalanced – how this works has changed since the Brixton release-train (Spring Cloud 1.1.0.RELEASE).
  3. Refactored configuration of Accounts microservice into its own class AccountsConfiguration.
  4. Upgraded to Spring Boot 2, so a few Boot classes have changed package.
  5. Upgraded demo application to Spring Cloud Finchley release-train (including various fixes from the comments at the end – thanks for the feedback).
  6. The Eureka server dependency has changed to spring-cloud-starter-netflix-eureka-server.

Previous version, using Spring Boot 1.5.10 and Spring Cloud Edgeware SR3, is available as git tag v1.2.0.

 

OK, let’s get started …

Service Registration

When you have multiple processes working together they need to find each other. If you have ever used Java’s RMI mechanism you may recall that it relied on a central registry so that RMI processes could find each other. Microservices has the same requirement.

The developers at Netflix had this problem when building their systems and created a registration server called Eureka (“I have found it” in Greek). Fortunately for us, they made their discovery server open-source and Spring has incorporated into Spring Cloud, making it even easier to run up a Eureka server. Here is the complete discovery-server application:

@SpringBootApplication
@EnableEurekaServer
public class ServiceRegistrationServer {

  public static void main(String[] args) {
    // Tell Boot to look for registration-server.yml
    System.setProperty("spring.config.name", "registration-server");
    SpringApplication.run(ServiceRegistrationServer.class, args);
  }
}

It really is that simple!

Spring Cloud is built on Spring Boot and utilizes parent and starter POMs. The important parts of the POM are:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <!-- Setup Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <!-- Setup Spring MVC & REST, use Embedded Tomcat -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <!-- Spring Cloud starter -->
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>
            <!-- Eureka for service registration -->
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
    </dependencies>

   <!-- Spring Cloud dependencies -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

This POM has changed since I originally wrote the article to use Spring Boot as its parent not Spring Cloud. Spring Cloud dependencies are provided via the dependency management section.

An sample gradle build file is also included in the github code.

Note: Finchley.RELEASE is the current “release train” – a set of co-ordinated releases — see note on Spring Cloud home page.

By default Spring Boot applications look for an application.properties or application.ymlfile for configuration. By setting the spring.config.name property we can tell Spring Boot to look for a different file – useful if you have multiple Spring Boot applications in the same project – as I will do shortly.

This application looks for registration-server.properties or registration-server.yml. Here is the relevant configuration from registration-server.yml:

# Configure this Discovery Server
eureka:
  instance:
    hostname: localhost
  client:  # Not a client, don't register with yourself (unless running
           # multiple discovery servers for redundancy)
    registerWithEureka: false
    fetchRegistry: false

server:
  port: 1111   # HTTP (Tomcat) port

By default Eureka runs on port 8761, but here we will use port 1111 instead. Also by including the registration code in my process I might be a server or a client. The configuration specifies that I am not a client and stops the server process trying to register with itself.

Using Consul

Spring Cloud also supports Consul as an alternative to Eureka. You start the Consul Agent (its registration server) using a script and then clients use it to find their microservices. For details, see this blog article or project home page.

Try running the RegistrationServer now (see below for help on running the application). You can open the Eureka dashboard here: http://localhost:1111 and the section showing Applications will be empty.

From now on we will refer to the discovery-server since it could be Eureka or Consul (see side panel).

Creating a Microservice: Account-Service

A microservice is a stand-alone process that handles a well-defined requirement.

Beans vs ProcessesWhen configuring applications with Spring we emphasize Loose Coupling and Tight Cohesion, These are not new concepts (Larry Constantine is credited with first defining these in the late 1960s – reference) but now we are applying them, not to interacting components (Spring Beans), but to interacting processes.

In this example, I have a simple Account management microservice that uses Spring Data to implement a JPA AccountRepository and Spring REST to provide a RESTful interface to account information. In most respects this is a straightforward Spring Boot application.

What makes it special is that it registers itself with the discovery-server at start-up. Here is the Spring Boot startup class:

@EnableAutoConfiguration
@EnableDiscoveryClient
@Import(AccountsWebApplication.class)
public class AccountsServer {

    @Autowired
    AccountRepository accountRepository;

    public static void main(String[] args) {
        // Will configure using accounts-server.yml
        System.setProperty("spring.config.name", "accounts-server");

        SpringApplication.run(AccountsServer.class, args);
    }
}

The annotations do the work:

  1. @EnableAutoConfiguration – defines this as a Spring Boot application.
  2. @EnableDiscoveryClient – this enables service registration and discovery. In this case, this process registers itself with the discovery-server service using its application name (see below).
  3. @Import(AccountsWebApplication.class) – this Java Configuration class sets up everything else (see below for more details).

What makes this a microservice is the registration with the discovery-server via @EnableDiscoveryClient and its YML configuration completes the setup:

# Spring properties
spring:
  application:
     name: accounts-service

# Discovery Server Access
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1111/eureka/

# HTTP Server
server:
  port: 2222   # HTTP (Tomcat) port

Note that this file

  1. Sets the application name as accounts-service. This service registers under this name and can also be accessed by this name – see below.
  2. Specifies a custom port to listen on (2222). All my processes are using Tomcat, they can’t all listen on port 8080.
  3. The URL of the Eureka Service process – from the previous section.

Eureka DashboardRun the AccountsServiceapplication now and let it finish initializing. Refresh the dashboard http://localhost:1111 and you should see the ACCOUNTS-SERVICE listed under Applications. Registration takes up to 30 seconds (by default) so be patient – check the log output from RegistrationService

Warning: Do not try to display XML output using the internal web-viewer of Eclipse/STS because it cannot do so. Use your favorite web browser instead.

For more detail, go here: http://localhost:1111/eureka/apps/ and you should see something like this:

<applications>
    <versions__delta>1</versions__delta>
    <apps__hashcode>UP_1_</apps__hashcode>
    <application>
        <name>ACCOUNTS-SERVICE</name>
        <instance>
            <hostName>autgchapmp1m1.corp.emc.com</hostName>
            <app>ACCOUNTS-SERVICE</app>
            <ipAddr>172.16.84.1</ipAddr><status>UP</status>
            <overriddenstatus>UNKNOWN</overriddenstatus>
            <port enabled="true">3344</port>
            <securePort enabled="false">443</securePort>
            ...
        </instance>
    </application>
</applications>

Alternatively go to http://localhost:1111/eureka/apps/ACCOUNTS-SERVICE and see just the details for AccountsService – if it’s not registered you will get a 404.

Configuration Options

Registration Time: Registration takes up to 30s because that is the default client refresh time. You can change this by setting the eureka.instance.leaseRenewalIntervalInSecondsproperty to a smaller number (in the demo application I have set it to 5). This is not recommended in production. See also.

eureka:
  instance:
    leaseRenewalIntervalInSeconds: 5         # DO NOT DO THIS IN PRODUCTION

Registration Id: A process (microservice) registers with the discovery-service using a unique id. If another process registers with the same id, it is treated as a restart (for example some sort of failover or recovery) and the first process registration is discarded. This gives us the fault-tolerant system we desire.

To run multiple instances of the same process (for load-balancing and resilience) they need to register with a unique id. When I first wrote this blog, that was automatic and since the Brixton release-train, it is again.

Under the Angel release train, the instance-id, used by a client to register with a discovery server, was derived from the client’s service name (the same as the Spring application name) and also the client’s host name. The same processes running on the same host would therefore have the same id, so only one could ever register.

Fortunately you could set the id property manually via the client’s Eureka metadata map, like this:

eureka:
  instance:
    metadataMap:
      instanceId: ${spring.application.name}:${spring.application.instance_id:${server.port}}

Since the Brixton release train, this is now the default. So what does it do?

We are setting the instanceId to application-name:instance_id, but if instance_id is not defined, we will use application-name::server-port instead. Note that the spring.application.instance_id is only set when using Cloud Foundry but it conveniently provides a unique id number for each instance of the same application. We can do something similar when running elsewhere by using the server-port (since different instances on the same machine must listen on different ports. Another example you will often see is ${spring.application.name}:${spring.application.instance_id:${random.value}} but I personally find using the port number makes each instance easy to identify – the random values are just long strings that don’t mean anything.

Note: The syntax ${x:${y}} is Spring property shorthand for ${x} != null ? ${x} : ${y}.

Since the Brixton release there is also a dedicated property for this:

eureka:
  instance:
    instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}

Accessing the Microservice: Web-Service

To consume a RESTful service, Spring provides the RestTemplate class. This allows you to send HTTP requests to a RESTful server and fetch data in a number of formats – such as JSON and XML.

Note: The Accounts microservice provides a RESTful interface over HTTP, but any suitable protocol could be used. Messaging using AMQP or JMS is an obvious alternative (in which case the Discovery Server is no longer needed – instead processes need to know the names of the queues to talk to, consider using the Spring Cloud Configuration Server for this).

Which formats can be used depends on the presence of marshaling classes on the classpath – for example JAXB is always detected since it is a standard part of Java. JSON is supported if Jackson jars are present in the classpath.

A microservice (discovery) client can use a RestTemplate and Spring will automatically configure it to be microservice aware (more of this in a moment).

Encapsulating Microservice Access

Here is part of the WebAccountService for my client application:

@Service
public class WebAccountsService {

    @Autowired        // NO LONGER auto-created by Spring Cloud (see below)
    @LoadBalanced     // Explicitly request the load-balanced template
                      // with Ribbon built-in
    protected RestTemplate restTemplate; 

    protected String serviceUrl;

    public WebAccountsService(String serviceUrl) {
        this.serviceUrl = serviceUrl.startsWith("http") ?
               serviceUrl : "http://" + serviceUrl;
    }

    public Account getByNumber(String accountNumber) {
        Account account = restTemplate.getForObject(serviceUrl
                + "/accounts/{number}", Account.class, accountNumber);

        if (account == null)
            throw new AccountNotFoundException(accountNumber);
        else
            return account;
    }
    ...
}

Note that my WebAccountService is just a wrapper for the RestTemplate fetching data from the microservice. The interesting parts are the serviceUrl and the RestTemplate.

Accessing the Microservice

As shown below, the serviceUrl is provided by the main program to the WebAccountController (which in turn passes it to the WebAccountService):

@SpringBootApplication
@EnableDiscoveryClient
@ComponentScan(useDefaultFilters=false)  // Disable component scanner
public class WebServer {

    // Case insensitive: could also use: http://accounts-service
    public static final String ACCOUNTS_SERVICE_URL
                                        = "http://ACCOUNTS-SERVICE";

    public static void main(String[] args) {
        // Will configure using web-server.yml
        System.setProperty("spring.config.name", "web-server");
        SpringApplication.run(WebServer.class, args);
    }

    @LoadBalanced    // Make sure to create the load-balanced template
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * Account service calls microservice internally using provided URL.
     */
    @Bean
    public WebAccountsService accountsService() {
        return new WebAccountsService(ACCOUNTS_SERVICE_URL);
    }

    @Bean
    public WebAccountsController accountsController() {
         return new WebAccountsController
                       (accountsService());  // plug in account-service
    }
}

A few points to note:

  1. The WebController is a typical Spring MVC view-based controller returning HTML. The application uses Thymeleaf as the view-technology (for generating dynamic HTML)
  2. WebServer is also a @EnableDiscoveryClient but in this case as well as registering itself with the discovery-server (which is not necessary since it offers no services of its own) it uses Eureka to locate the account service.
  3. The default component-scanner setup inherited from Spring Boot looks for @Componentclasses and, in this case, finds my WebAccountController and tries to create it. However, I want to create it myself, so I disable the scanner like this @ComponentScan(useDefaultFilters=false).
  4. The service-url I am passing to the WebAccountController is the name the service used to register itself with the discovery-server – by default this is the same as the spring.application.name for the process which is account-service – see account-service.yml above. The use of upper-case is not required but it does help emphasize that ACCOUNTS-SERVICE is a logical host (that will be obtained via discovery) not an actual host.

Load Balanced RestTemplate

The RestTemplate bean will be intercepted and auto-configured by Spring Cloud (due to the @LoadBalanced annotation) to use a custom HttpRequestClient that uses Netflix Ribbon to do the microservice lookup. Ribbon is also a load-balancer so if you have multiple instances of a service available, it picks one for you. (Neither Eureka nor Consul on their own perform load-balancing so we use Ribbon to do it instead).

Note: From the Brixton Release Train (Spring Cloud 1.1.0.RELEASE), the RestTemplate is no longer created automatically. Originally it was created for you, which caused confusion and potential conflicts (sometimes Spring can be too helpful!).

Note that this instance is qualified using @LoadBalanced. (The annotation is itself annotated with @Qualifier – see here for details). Thus if you have more than one RestTemplate bean, you can make sure to inject the right one, like this:

@Autowired
    @LoadBalanced     // Make sure to inject the load-balanced template
    protected RestTemplate restTemplate;

If you look in the RibbonClientHttpRequestFactory you will see this code:

String serviceId = originalUri.getHost();
    ServiceInstance instance =
             loadBalancer.choose(serviceId);  // loadBalancer uses Ribbon
    ... if instance non-null (service exists) ...
    URI uri = loadBalancer.reconstructURI(instance, originalUri);

The loadBalancer takes the logical service-name (as registered with the discovery-server) and converts it to the actual hostname of the chosen microservice.

RestTemplate instance is thread-safe and can be used to access any number of services in different parts of your application (for example, I might have a CustomerService wrapping the same RestTemplate instance accessing a customer data microservice).

Configuration

Below the relevant configuration from web-server.yml. It is used to:

  1. Set the application name
  2. Define the URL for accessing the discovery server
  3. Set the Tomcat port to 3333
# Spring Properties
spring:
  application:
     name: web-service

# Discovery Server Access
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1111/eureka/

# HTTP Server
server:
  port: 3333   # HTTP (Tomcat) port

How to Run the Demo

A small demo of this system is at http://github.com/paulc4/microservices-demo. Clone it and either load into your favorite IDE or use maven directly. Suggestions on how to run the demo are included in the README on the project homepage.


Extra Notes

Some notes about Spring Boot usage by these applications. If you are not familiar with Spring Boot, this explains some of the “magic”!

View Templating Engines

The Eureka dashboard (inside RegistrationServer) is implemented using FreeMarker templates but the other two applications use Thymeleaf. To make sure each uses the right view engine, there is extra configuration in each YML file.

This is at the end of registration-server.yml to disable Thymeleaf.

...
# Discovery Server Dashboard uses FreeMarker.  Don't want Thymeleaf templates
spring:
  thymeleaf:
    enabled: false     # Disable Thymeleaf spring:

Since both AccountService and WebService use thymeleaf, we also need to point each at their own templates. Here is part of account-server.yml:

# Spring properties
spring:
  application:
     name: accounts-service  # Service registers under this name
  freemarker:
    enabled: false      # Ignore Eureka dashboard FreeMarker templates
  thymeleaf:
    cache: false        # Allow Thymeleaf templates to be reloaded at runtime
    prefix: classpath:/accounts-server/templates/
                        # Template location for this application only
...

web-server.yml is similar but its templates are defined by

   prefix: classpath:/web-server/templates/

Note the / on the end of each spring.thymeleaf.prefix classpath – this is crucial.

Command-Line Execution

The jar is compiled to automatically run io.pivotal.microservices.services.Main when invoked from the command-line – see Main.java.

The Spring Boot option to set the start-class can be seen in the POM:

<properties>
        <!-- Stand-alone RESTFul application for testing only -->
        <start-class>io.pivotal.microservices.services.Main</start-class>
    </properties>

AccountsConfiguration class

@SpringBootApplication
@EntityScan("io.pivotal.microservices.accounts")
@EnableJpaRepositories("io.pivotal.microservices.accounts")
@PropertySource("classpath:db-config.properties")
public class AccountsWebApplication {
...
}

This is the main configuration class for AccountService which is a classic Spring Boot application using Spring Data. The annotations do most of the work:

  1. @SpringBootApplication – defines this as a Spring Boot application. This convenient annotation combines @EnableAutoConfiguration@Configuration and @ComponentScan(which, by default, causes Spring to search the package containing this class, and its sub-packages, for components – potential Spring Beans: AccountController and AccountRepository) .
  2. @EntityScan("io.pivotal.microservices.accounts") – because I am using JPA, I need to specify where the @Entity classes are. Normally this is an option you specify in JPA’s persistence.xml or when creating a LocalContainerEntityManagerFactoryBean. Spring Boot will create this factory-bean for me because the spring-boot-starter-data-jpadependency is on the class path. So an alternative way of specifying where to find the @Entity classes is by using@EntityScan. This will find Account.
  3. @EnableJpaRepositories("io.pivotal.microservices.accounts")– look for classes extending Spring Data’s Repository marker interface and automatically implement them using JPA – see Spring Data JPA.
  4. @PropertySource("classpath:db-config.properties") – properties to configure my DataSource – see db-config.properties.

Configuring Properties

As mentioned above, Spring Boot applications look for either application.properties or application.yml to configure themselves. Since all three servers used in this application are in the same project, they would automatically use the same configuration.

To avoid that, each specifies an alternative file by setting the spring.config.name property.

For example here is part of WebServer.java.

public static void main(String[] args) {
  // Tell server to look for web-server.properties or web-server.yml
  System.setProperty("spring.config.name", "web-server");
  SpringApplication.run(WebServer.class, args);
}

At runtime, the application will find and use web-server.yml in src/main/resources.

Logging

Spring Boot sets up INFO level logging for Spring by default. Since we need to examine the logs for evidence of our microservices working, I have raised the level to WARN to reduce the amount of logging.

To do this, the logging level would need to be specified in each of the xxxx-server.ymlconfiguration files. This is usually the best place to define them as logging properties cannotbe specified in property files (logging has already been initialized before @PropertySource directives are processed). There is a note on this in the Spring Boot manual, but it’s easy to miss.

Rather than duplicate the logging configuration in each YAML file, I instead opted to put it in the logback configuration file, since Spring Boot uses logback – see src/main/resources/logback.xml. All three services will share the same logback.xml.

Source: https://spring.io/blog/2015/07/14/microservices-with-spring

 

*************************************************************************************************************************************************

 

Microservices Implementation in Java

Feb 27, 2018

Microservices is a synonym for Service Oriented Architectural (SOA) style of constructing aggregation of many small loosely coupled services. When developing microservices with java, you can use several microservices framework. Some of the frameworks are Spring Boot, Jersey, Dropwizard, Play Framework, and Restlet. In this document, we will implement a microservice “authenticate” with Spring Boot. Spring Boot is the best and most used Microservice framework since long.

Microservices in JAVA

The advantage of Spring Boot is that it has a vast infrastructure and has many spring projects working along. To create microservices with Spring Boot, you need to follow below mentioned 3 steps:

  • Setup new service
  • Expose the resource using RestController
  • Consume the service resource with RestTemplate

Here, we are going to create 3 different microservices. First microservice is Discovery Server which is a Eureka server. Second microservice is Authentication Service which is Producer service and Third microservice is Consumer service which is discovery client. This microservice can find other microservices using its RestTemplate. Let’s start with developing these three microservices.

Developing Discovery Server

Service Discovery is used so that microservices can find each other. We use Eureka for our service discovery. Eureka, created by Netflix, provides service discovery with Spring Cloud. Folder Structure for Discovery server is as below:folder structureMaven Dependency:

<parent>
	<groupid>org.springframework.boot</groupid>
	<artifactid>spring-boot-starter-parent</artifactid>
	<version>1.5.3.RELEASE</version>
</parent>
<dependencies>
	<dependency>
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter</artifactid>
	</dependency>
	<dependency> <!-- Eureka registration server -->
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter-eureka-server</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-web</artifactid>
	</dependency>
</dependencies>
<dependencymanagement>
	<dependencies>
		<dependency>
			<groupid>org.springframework.cloud</groupid>
			<artifactid>spring-cloud-dependencies</artifactid>
			<version>Camden.SR5</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencymanagement>

Application.yml:

eureka: # Configure this Discovery Server
	instance:
		hostname: localhost
	client: 
		registerWithEureka: false
		fetchRegistry: false
server: # HTTP (Tomcat) port
	port: 9000

To run Eureka registry service is easy, just define @EnableEurekaServer annotation to spring boot application.

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServerApplication {
	public static void main(String[] args) {
		SpringApplication.run(DiscoveryServerApplication.class, args);
	}
}

After running this microservice, following output is available on localhost:9000: tsblogHere in the application section of the image, there is no instance currently available with Eureka. After running Producer and Consumer microservice, we will able to see the instances in the Application section.

Developing Authentication Service

In this, we will create Login and Registration methods. We will use Spring Data JPA for querying MySQL database using method name convention. You can learn spring data JPA from this site: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/. Also in this, we will be hashing the password using Spring Security’s BCrypt algorithm. Folder Structure for Authentication service is as below:tsblog2Maven Dependency:

<dependencies>
	<dependency>
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter-eureka</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-web</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-data-jpa</artifactid>
	</dependency>
	<dependency>
		<groupid>mysql</groupid>
		<artifactid>mysql-connector-java</artifactid>
	</dependency>
</dependencies>

Application.yml:

spring: # Service registers under this name
	application:
		name: authentication-service
	datasource: # MySql credentials
		url: jdbc:mysql://127.0.0.1:3306/test
		username: root
		password: root
	jpa: # JPA support
		show-sql: true
		hibernate:
			ddl-auto: validate
			use-new-id-generator-mappings: false
		properties:
			hibernate:
			dialect: org.hibernate.dialect.MySQLDialect
eureka: # Discovery Server Access
	client:
		serviceUrl:
			defaultZone: http://localhost:9000/eureka/
server: # HTTP Server (Tomcat) Port
	port: 9001

To define this microservice as Discovery Client, we need to include @EnableDiscoveryClient annotation to application.

@SpringBootApplication
@EnableDiscoveryClient
public class AuthenticationClientApplication {
	public static void main(String[] args) {
		SpringApplication.run(AuthenticationClientApplication.class, args);
	}
}

We will create AuthenticationRepository to querying the database using JPA. To expose Authentication service, we use RestController. In the controller, @CrossOrigin annotation is used to pass data or get data from cross platforms like Angular.

@RestController
@CrossOrigin
public class AuthenticationController {
	@Autowired
	private AuthenticationRepository repo;
	@RequestMapping(&quot;/api/getUsers&quot;)
	public @ResponseBody List<userauthenticationbean> getUsers() {
		return repo.findAll();
	}
	@RequestMapping(value = &quot;/api/addUser&quot;,method = RequestMethod.POST)
	public @ResponseBody UserAuthenticationBean addStudent(@RequestBody UserAuthenticationBean user) {	// Hashing the password using BCrypt of Spring Security 
		String hashed_password = BCrypt.hashpw( user.getPassword(), BCrypt.gensalt(12) ); 
		UserAuthenticationBean newuser = new UserAuthenticationBean();
		newuser.setUserName(user.getUserName());
		newuser.setPassword(hashed_password);
		return repo.save(newuser);
	}
	@RequestMapping(value = &quot;/api/getUser&quot; ,method = RequestMethod.POST)
	public @ResponseBody UserAuthenticationBean getByUser(@RequestBody UserAuthenticationBean user) {
		UserAuthenticationBean userget = repo.findByUserName(user.getUserName());
		// Comparing Hashed password with given password
		If ( BCrypt.checkpw( user.getPassword(), userget.getPassword() ) ){
			return userget;
		} return null;
	} 
}
</userauthenticationbean>

After running this microservice, you can fire rest call to this service on localhost:9001. Also, instance of this service gets registered in eureka server which is already running on localhost:9000.

Developing Consumer Service

In this service, we will use RestTemplate to consume the remote service resource. Also we use Spring Cloud’s Netflix support for load balancing. Load balancing is used to decide which service instance to use. Netflix Ribbon provides several algorithms for client-side load balancing. Folder Structure for Consumer service is as below:tsblog3Maven Dependency:

<dependencies>
	<dependency>
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter-eureka</artifactid>
	</dependency>
	<dependency> <!-- Netflix Ribbon used for Load Balancing -->
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter-ribbon</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-web</artifactid>
	</dependency>
</dependencies>

Application.yml:

spring: # Service registers under this name
	application:
		name: consumer-service
eureka: # Discovery Server Access
	client:
		serviceUrl:
			defaultZone: http://localhost:9000/eureka/
server: # HTTP Server (Tomcat) Port
	port: 8081

You need to include RemoteRepository bean and RestTemplate bean in main application, so that this microservice can consume other microservices.

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerServiceApplication {
 
	public static final String AUTHENTICATION_SERVICE_URL = &quot;http://AUTHENTICATION-SERVICE&quot;;
 
	public static void main(String[] args) {
		SpringApplication.run(ConsumerServiceApplication.class, args);
	}
 
	@Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
 
	@Bean
	public AuthenticationRepository authenticationRepository(){
		return new RemoteAuthenticationRepository(AUTHENTICATION_SERVICE_URL);
	}
}

RemoteRepository will pass the HTTP request to the given Service URL and get the response from the remote service.

public class RemoteAuthenticationRepository implements AuthenticationRepository {
	@Autowired
	@LoadBalanced
	protected RestTemplate restTemplate;
	protected String serviceUrl;
 
	public RemoteAuthenticationRepository(String serviceUrl) {
		this.serviceUrl = serviceUrl.startsWith(&quot;http&quot;) ? serviceUrl : &quot;http://&quot; + serviceUrl;
	}
	@Override
	public List<userauthenticationbean> findAll() {
		UserAuthenticationBean[] users = restTemplate.getForObject(serviceUrl+"/api/getUsers", UserAuthenticationBean[].class);
		return Arrays.asList(users);
	}
 
	@Override
	public UserAuthenticationBean findByUserNameAndPassword(String userName, String password) {
		UserAuthenticationBean user= new UserAuthenticationBean(); 
		user.setPassword(password);
		user.setUserName(userName);
		return restTemplate.postForObject(serviceUrl + &quot;/api/getUser&quot;,user,UserAuthenticationBean.class);
	}
 
	@Override
	public UserAuthenticationBean save(UserAuthenticationBean user) {
		return restTemplate.postForObject(serviceUrl + &quot;/api/addUser&quot;, user, UserAuthenticationBean.class);
	}
}
</userauthenticationbean>

After running this service on localhost:8081, you can fire HTTP request from client side and request to this service will be passed to producer microservice, in our scenario Authentication service. Also, you will be able to see instance of this microservice in Eureka server on localhost:9000 as below:tsblog4To summarize, we understand about using microservices with Spring Boot. Also we learned some information on Eureka server and Netflix Ribbon for discovery service and Load balancing. You can learn more about microservices with spring from site: https://spring.io/blog/2015/07/14/microservices-with-spring

Source: https://www.tatvasoft.com/blog/microservices-implementation-java/

 

****************************************************************************************************************************************************

 

Java microservices architecture by example: When a monolith doesn’t work

java microservices

Microservices are not something new. However, this architectural approach continues to stir up interest. It claims to be a good choice for so much needed today heavy load handling and can already boast successful implementations by such big players as Google, Netflix, Amazon, and eBay.

In this article, we’ll explore a real-life example to understand the essence of microservices, the way their inner-system communication happens and the differences this architectural approach brings to the application.

A quick introduction to microservices

A microservices architecture is a particular case of a service-oriented architecture (SOA). SOA applies to the systems built with several independently deployable modules. What sets microservices apart is the extent to which these modules are interconnected. Microservices are even more independent and tend to share as little elements as possible. Every server comprises just one certain business process and never consists of several smaller servers.

Microservices become handy when one server is not enough, which happens, for example, if a server can’t handle heavy load intended for it, or if its memory use is too high. Microservices also bring a set of additional benefits, such as easier scaling, the possibility to use multiple programming languages and technologies, and others.

However, as the architecture description may sound quite vague in words, let us demonstrate how it works with a real Java-based application example. Why Java? Java is a frequent choice for building a microservices architecture as it is a mature language tested over decades and has a multitude of microservices-favorable frameworks, such as legendary Spring, Jersey, Play, and others.

So, let’s have a look at the example based on our real project – a mobile retail application that logs a user into their profile, takes orders, and sends email notifications (order confirmation, shipping updates, etc.) – and see what happens behind the scenes.

To make microservices’ distinguishing traits more explicit, we’re going to fresh up how things go with traditionally used monoliths.

What might happen with a monolith

A monolithic architecture keeps it all simple. An app has just one server and one database. The program consistently implements all business logic step by step, moving to the next stage only after the previous one is completed. All the connections between units are inside-code calls. When the user opens it to make an order, the system checks security, logs them in, takes their order, sends an e-mail order confirmation and only after all these steps are performed, the user will see the order done, and the session will be completed.

What’s wrong?

Nothing is wrong. The application works, there are just some problems you may face:

× Complete shutdown. If one part of a business logic server doesn’t work or is overloaded, the whole application may stop as it can’t proceed with the next operational stage. Back to our example, if, for some reason, notifications cannot be sent right away, the users can’t see their order successfully finished till this part of the business logic server becomes available again.

× Complicated updates. If you want to upgrade your application (introduce new technologies, add new features), even in case of minor changes, a development team will have to rewrite pretty much of it, then stop the old version for some time (which means lost clients and orders) and introduce a new one. Moreover, the development team will have to be very careful with newly introduced changes because they may damage the whole program. Also, the new parts should be necessarily written in the language of the initial system or at least in the one compatible with it.

× Frustrating UX. As a monolith continues to develop and grow and needs to deal with higher and higher load, it turns into a big and slow application with increasingly high latency, which will keep customers away as they won’t wait and may consider buying from competitors.

To tackle high load, you could duplicate the existing business logic server to get two identical servers and spread the load between them with a dynamic balancer that will randomly forward requests to the less loaded one of them. It means that, if, initially, one server processes, let’s say, 200K queries per second, which makes it too slow, now each of them deals with 100K QPS without experiencing overload. Nevertheless, it’s not a microservices architecture yet, even though there are several servers. What is more, two other problems remained unresolved: shutdowns and problematic updates.

This compels us to seek another solution.

What changes with microservices

And here we finally turn to our microservices-based example, where we designate each independent server to perform a certain business function. Here’s how we can manage to save the day with a microservices architecture.

example of java microservices architecture

Step 1. Split it

We split our application into microservices and got a set of units completely independent for deployment and maintenance. In our application, 2 user profile servers, 3 order servers and a notification server perform the corresponding business functions. Each of microservices responsible for a certain business function communicates either via sync HTTP/REST or async AMQP protocols.

Step 2. Pave the ways

Splitting is only the starting point of building a microservice-oriented architecture. To make your system a success, it is more important and still even more difficult to ensure seamless communication between newly created distributed components.

First of all, we implemented a gateway. The gateway became an entry point for all clients’ requests. It takes care of authentication, security check, further routing of the request to the right server as well as of the request‘s modification or rejection. It also receives the replies from the servers and returns them to the client. The gateway service exempts the client side from storing addresses of all the servers and makes them independently deployable and scalable. We also set the Zuul 2 framework for our gateway service so that the application could leverage the benefits of non-blocking HTTP calls.

Secondly, we’ve implemented the Eureka server as our server discovery that keeps a list of utilized user profile and order servers to help them discover each other. We also backed it up with the Ribbon load-balancer to ensure the optimal use of the scaled user profile servers.

The introduction of the Hystrix library helped to ensure stronger fault tolerance and responsiveness of our system isolating the point of access to a crashed server. It prevents requests from going into the void in case the server is down and gives time to the overloaded one to recover and resume its work.

We also have a message broker (RabbitMQ) as an intermediary between the notification server and the rest of the servers to allow async messaging in-between. As a result, we don’t have to wait for a positive response from the notification server to proceed with work and have email notifications sent independently.

Let’s now review the monolith problems we could come across and see what happens with them in our microservices-based application:

Complete shutdown

  • If one server goes slow because of overload or crashes completely, the life won’t stop and, often, the user won’t even notice any braking. The system will either re-route the requests to its substitutes (as we have 2 user profile servers and 3 order servers) or proceed with its work and resume the function as soon as the server is recovered (in case of our notification server crashes). Maybe the client won’t get notifications right away, but at least they won’t have to look at the ‘pre-loader’ for ages.

Complicated updates

  • Now we can easily update what we need. As the units are completely independent, we just re-write the needed servers to add some new features (recommendation engine, fraud detection, etc.). In our example, to introduce an IP tracker and report suspicious behavior (as Gmail does), we create fraud detection server and slightly modify our user profile servers while the rest of the servers safely stays intact.

Frustrating UX

  • Loosely coupled nature of our microservices architecture and its incredible potential for scaling allows tackling incidents with minimal negative effect on user experience. For example, when we see that some of our core features run slow, we can scale the number of servers handling it (as we did from the start with user profile and order servers) or let them go a little slow for a while, if the features are not vital (as we did with notifications). In some other cases, it makes sense to skip them at all in peak times (as it happens with pop-ups that, for a while, show only textual description with no image included).

In closing

The real-life example proves that, though not magic, microservices can definitely help when it comes to creating complex applications that deal with huge loads and need continuous improvement and scaling. However, like any other architectural approach, they are not entirely flawless, so figure out whether the above-mentioned traits are actually relevant to your future application, carefully sum up all pros and cons and get professional advice, because the ‘splitting-for-splitting’ may not only turn out to be useless but also have negative effects on your application.

Source: https://www.scnsoft.com/blog/java-microservices-example

Spring Boot and WordPress CMS Integration

https://kamranzafar.org/2016/08/08/spring-boot-and-wordpress-integration/

 

There are a lot of excellent open source content management systems available today,  WordPress being one of them, which is widely used. WordPress is a PHP based CMS so not a lot of cohesion is available with other technologies like Java, and is simply ignored as a viable content management option just for being non-Java.

In this post I will demonstrate how WordPress can be integrated with Spring Boot applications, all made possible with WordPress REST plugin and a Spring client. Both of these are open source and available for free. Below is a simple design diagram that explains how this integration works. This post assumes that the reader has prior knowledge of WordPress and Spring Boot.


spring-wpapi-simple
First install and activate WP-API v2 plugin on the WordPress site. After activation, you could verify that the plugin is working by accessing http://yoursite/wp-json/wp/v2/posts, which should display all the posts in JSON format.In the spring boot application add the following dependency in order to include the Spring WP-API client.

Below is a sample configuration we need in the application.properties file, so that we can connect our Spring Boot application to our WordPress site.

The Spring WP-API client needs the RestTemplate so lets create a bean in our Application and autowire the Spring client. We also need to add component scan annotation so that Spring finds and autowires all the required dependencies.

Now our spring boot application is all setup to connect to out WordPress site in order to retrieve and create content. So lets try and lookup all the posts having the keyword “Spring”, below is how we can do this.

The complete test application is available with the Spring WP-API client on Github.

This is just a small example of how we can integrate Spring Boot and WordPress. We can take this further by properly integrating WordPress in the Spring web applications platform, e.g. by enabling Single Sign On using the CAS plugin.


spring-wpapi-cas
And we can evolve this design even further by having a second-level content storage, like a database or an in-memory caching solution etc. This storage can serve as a cache and can also be used for additional configuration, so that we display relevant content faster in our Spring applications.

spring-wpapi-cas-db
For more information please see the documentation of the WordPress REST plugin and Spring WP-API client.

How to Create Spring Boot Application Step by Step

http://www.adeveloperdiary.com/java/spring-boot/create-spring-boot-application-step-step/

 

How to Create Spring Boot Application Step by Step

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageShare on TumblrShare on Reddit

Spring Boot had been built for Rapid Application Development. In this tutorial we will learn How to Create Spring Boot Application using some easy examples. We will also focus on How to deploy spring boot application in different application servers.

Here are the following topics that we will cover in this series:

  1. Create Spring Boot Application using
    • start.spring.io
    • Eclipse STS
    • IntelliJ IDEA STS
  2. Run Spring Boot Application using
    • Java CLI
    • Eclipse/IntelliJ IDEA
  3. Create a Basic Spring Boot application using REST
  4. How to use Spring Actuator
  5. Deploy Spring Boot application in
    • IBM Liberty Profile
    • IBM Application Server 8.5

If you need an introduction of Spring Boot please find my previous post below.

Create Spring Boot Application using start.spring.io

The best way of bootstrapping Spring Boot application is by using Spring Initializr. Let’s first start by opening http//start.spring.io.As you already know, you can use either Maven or Gradle to build, however we will use Maven in this tutorial. Click on Switch to the full Version and you will be able to see the below screen.

Software Needed

  • JDK 1.8 (You can use 1.7 or 1.6)
  • Maven 3.x

Steps :

  • Select Maven Project
  • If you want, change the Group/Package name. We will use com.adeveloperdiary
  • Change the Artifact to SpringBoot, Name will automatically change to the same
  • Leave the packaging to Jar, Java Version to 1.8 (Make sure you have JDK 1.8 in your local or use 1.7 )
  • Either type the Dependencies or select them below. We will add Web and Actuator here
  • Click on Generate Project button to download the zip file

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Now Extract the zip and you will have the following files.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Open Terminal and navigate to the above folder. Type mvn clean packageand press enter. The Build will start now.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Once the build has been completed, you will have the SpringBoot-0.0.1-SNAPSHOT.jar created inside the target folder.

The Size of the jar would be around 13MB since it will have the embedded Tomcat server in it.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create Spring Boot Application using Eclipse

We will use STS Toolkit to bootstrap when using eclipse. I am using eclipse MARS .1 version. We will first install the STS (SpringSource Tools Suite). Open Eclipse Marketplace, Type STS in Find and install the STS.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Then open Spring perspective.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create a New -> Spring Starter Project.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the following details. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Select Web and Actuator. Click on Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Click on Finish.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

This should create the Spring Boot Project in Eclipse.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Create Spring Boot Application using IntelliJ IDEA

We will now use IntelliJ IDEA to create our Spring Boot Application.I recommend to use the latest version of IntelliJ. Create a New Project. Select Spring Initializr. Click on Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the following details. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Select Web and Actuator. Click Next.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Enter the project Name and click Finish.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Your Spring Boot Project has been created now.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application using CLI

We had created the jar file, now we will run it from Command Line by executing this line

You should be able to see Spring Boot in the Command Line.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

The server should have started and the default port number will also be displayed as below.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application in Eclipse

Its much easier to run the Spring Boot app in eclipse. Select the project, Right Click and, move to Run As and click on Spring Boot App. Again, remember you need to select the project to get this option, not the pom file.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Here is the output.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Run Spring Boot Application in IntelliJ IDEA

Its probably most easy, click on the run icon.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

You should be able to see the logs that the application has started.

How to Create Spring Boot Application Step by Step adeveloperdiary.com

Conclusion

Hope this Step by Step approach will help you. Next we will learn how to create RESTServices and use Actuator in Spring Boot. Later we will also learn how to deploy Spring Boot Application in IBM Liberty Profile and IBM WAS 8.5 Server.

This is the 2nd part of Getting Started with Spring Boot Series. Find all the parts here.

  1. An Introduction to Spring Boot
  2. How to Create Spring Boot Application Step by Step
  3. How to create RESTFul Webservices using Spring Boot
  4. How to deploy Spring Boot application in IBM Liberty and WAS 8.5

Step-by-step Spring Boot RESTful web services example in Java using STS

https://www.theserverside.com/video/Step-by-step-Spring-Boot-RESTful-web-services-example-in-Java

In a previous article about important RESTful principles and how to create a beautiful RESTful API, I used the example of a web service that kept track of an ongoing, global score for an online rock-paper-scissors application. In this step-by-step Spring Boot RESTful web services example, we’ll implement that scenario using the Spring Web APIs and the Eclipse based SpringSource Tool Suite (STS) as the IDE.

Review of the RESTful API

The RESTful score service will provide the following functions:

RESTful clients can find out the current number of wins, losses and ties through a GET request to the following URL:

www.mcnz.com/rps/score | GET

This invocation will return a JSON string in the following format:

{ "wins":"5", "losses":"3", "ties": "0"}

RESTful clients can update the score by invocating the same URL through a PUT invocation while also passing query parameters. Again, the program will return a JSON-based representation of the score after the update. A better design would be to use JSON as the payload, but query parameters are used here for the sake of simplicity.

www.mcnz.com/rps/score?wins=1&losses=2&ties=3 | PUT

With the RESTful API, the user cannot directly set the number of wins, losses or ties. The client can only use a POST invocation to increment values one at a time. This is not an idempotent function, so it is handled through a POST. In this case, a simple number is returned to the program as opposed to a JSON string.

You can use a simple GET invocation on the appropriate resource locator to obtain the number of wins, losses or ties:

www.mcnz.com/rps/score/wins | GET

www.mcnz.com/rps/score/ties | GET

www.mcnz.com/rps/score/losses | GET

This step-by-step Spring Boot RESTful web services example in Java has very few prerequisites, but it does assume that you have the SpringSource Tool Suite (STS) installed. If that’s the case, you are ready to jump on the fast track to developing RESTful web services with Spring.

Step 1. Create the RESTful Spring Boot project

The first step in this exercise is to create a new Spring Boot project named restful-spring-example that uses both the Web and DevTools features. This is accomplished by kicking off the Spring Starter Project wizard in Eclipse. Select the Spring Web and DevTools options and click Finish on the Spring Boot project wizard.

Spring Boot project wizard
How to start a Spring Boot RESTful web services project

Step 2: Create the Java classes

The next step is to open the restful-spring-example project and create two classes: Score.java and ScoreService.java.

Right click on the com.mcnz.restful.spring.boot package and choose to create a new class named Score. The Score class is used to keep track of the global number of wins, losses and ties that occur in the online rock-paper-scissors game. The Score class will maintain the number of wins, losses and ties as static variables of type int. State should never be held within a RESTful web service, so this class represents the externalization of state.

package com.mcnz.restful.spring.boot;

public class Score {
  public static int WINS, LOSSES, TIES;
}

After you code the Score class, create a second Java component named ScoreService. We’ll use the ScoreService class to provide access to — and the ability to manipulate — the Score. The first iteration of the class used in this Spring Boot web service example will have getter methods that return the number of wins, losses and ties, along with update methods that can increment the number of wins, losses and ties by one.

Create the RESTful Spring Boot ScoreService class
How to create the ScoreService class for the step-by-step RESTful web services example

Here is the first iteration of the ScoreService class before we decorate it with RESTful annotations and subsequently configure it as a Spring Boot web service.

package com.mcnz.restful.spring.boot;
/* Spring Boot web service example class */
public class ScoreService {
   
   public String updateScore(int wins, int losses, int  ties) {
      Score.WINS = wins;
      Score.TIES = ties;
      Score.LOSSES = losses;
      /* to be updated to return JSON */
      return this.toString();
   }

   public int increaseWins()   { return ++Score.WINS;   }
   public int increaseTies()   { return ++Score.TIES;   }
   public int increaseLosses() { return ++Score.LOSSES; }

   public int getWins()   { return Score.WINS;   }
   public int getTies()   { return Score.TIES;   }
   public int getLosses() { return Score.LOSSES; }
}

/* End of Spring Boot web service example class. */

Step 3: Annotate the Spring Boot example class

With the first iteration of the ScoreService component coded, the next step is to transform it into a Spring Boot RESTful web service by decorating the class declaration with the @RestController annotation. The @RestController annotation informs the Spring Boot framework that the class contains methods that will be invoked through a web-based resource URL.

@RestController
public class ScoreService { … }

Step 4: Annotate RESTful Spring methods

Step four is to add @RequestMapping annotations to methods. These annotations define the HTTP method used along with the structure of the resource URLs that will be used to invoke them. In the previous tutorial about how to create beautiful RESTful APIs, we established that we would invoke the update methods through a POST, and all getter methods sensibly through a GET invocation. The URLs are all resource based, so use of the URL path is /score/wins to get information about the number of wins and the path /score/ties to increase the number of ties.

Fully decorated with Spring Boot RESTful web service annotations, the next iteration of the ScoreService class looks as follows:

/* Spring Boot web service example class */
@RestController
public class ScoreService {

  @RequestMapping(value="/score", method=RequestMethod.PUT, )
  public String updateScore(int wins, int losses, int ties) {
     Score.WINS = wins;
     Score.TIES = ties;
     Score.LOSSES = losses;
     return this.toString(); /* to be updated to return JSON */
   }
   @RequestMapping(value="/score/wins", method=RequestMethod.POST)
   public int increaseWins()   { return ++Score.WINS;   }
  
   @RequestMapping(value="/score/ties", method=RequestMethod.POST)
   public int increaseTies()   { return ++Score.TIES;   }

   @RequestMapping(value="/score/losses", method=RequestMethod.POST)
   public int increaseLosses() { return ++Score.LOSSES; }

   @RequestMapping(value="/score/wins", method=RequestMethod.GET)
   public int getWins()   { return Score.WINS;   }

   @RequestMapping(value="/score/ties", method=RequestMethod.GET)
   public int getTies()   { return Score.TIES;   }

   @RequestMapping(value="/score/losses", method=RequestMethod.GET)
   public int getLosses() { return Score.LOSSES; }
}
/* End of Spring Boot web service example class */

Step 5: Generate RESTful JSON responses

This step-by-step Spring Boot RESTful web services example needs to generate a JSON-based response for the client. There are excellent frameworks like Jackson and GSON, which you should use in larger projects, but for this simple RESTful web services example, we will simply employ some Java String manipulation to generate the JSON.

The getScore() method needs to return a JSON string formatted in the following manner:

{ "wins":"5", "losses":"3", "ties": "0"}

Here is how the un-annotated getScore() method looks when coded to return a JSON string:

public String getScore() {
  String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,Score.WINS, Score.LOSSES, Score.TIES);
}

Note that you’ll use this same pattern match and String format approach again to return a JSON-based representation of the score in the updateScore method.

Since the getScore() method now returns JSON, you need to add a new produces attribute to the @RequestMapping annotation. The fully annotated getScore() method that indicates that JSON will be returned to the calling program looks as follows:

@RequestMapping(value="/score", 
            method=RequestMethod.GET, 
                  produces=MediaType.APPLICATION_JSON_VALUE)
public String getScore() {
  String pattern = 
       "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,  Score.WINS, Score.LOSSES, Score.TIES);
}

In order to generate JSON, the updateScore method follows a similar pattern of updated annotations and String manipulation within the code:

@RequestMapping(value="/score", 
    method=RequestMethod.PUT, 
       produces=MediaType.APPLICATION_JSON_VALUE)

public String updateScore(int wins, int losses, int ties) {
  Score.WINS = wins;
  Score.TIES = ties;
  Score.LOSSES = losses;
 String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern,Score.WINS, Score.LOSSES, Score.TIES);     
}

QueryParam to method signature mapping

To update the ScoreService, the client will use the /score path while it passes query parameters to represent the number of wins, losses and ties. For example, a request to update the number of wins to 99, ties to 88 and losses to 7 would look like this:

http://www.mcnz.com/score?wins=99&ties=88&losses=7

As long as the updateScore method has method parameters that match the names of the query parameters, the Spring Boot web services framework will assign the queryParam values to the correspondingly named method signature parameter.

http://www.mcnz.com/score?wins=99&ties=88&losses=7

public String updateScore(int wins, int losses, int ties) { … }

The updateScore method will take the values passed into the method and assign them to the corresponding properties of the ScoreService class. An updated JSON string will be sent to the client indicating the new, updated value of the score. You’ll use the same process used to generate JSON in the getScore()method here. The full method implementation is as follows:

@RequestMapping(value="/score", 
     method=RequestMethod.PUT, 
        produces=MediaType.APPLICATION_JSON_VALUE)

public String updateScore(int wins, int losses, int ties) {
  Score.WINS = wins;
  Score.TIES = ties;
  Score.LOSSES = losses;
  String pattern = 
     "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
  return String.format(pattern, Score.WINS, Score.LOSSES, Score.TIES);
}

With the updateScore method coded, the step-by-step Spring Boot RESTful web services example is code complete, and the only steps left are to test and deploy.

Step 6:  Run the Spring Boot RESTful web service

To run the application, simply right click on the restful-spring-example project and choose Run As → Spring Boot App and Maven will package the application and deploy it to the STS server. When the console window indicates the Tomcat-based server has finished starting, open a browser window and go to localhost:8080/score/wins. A value of zero will appear.

Step 7: Test the RESTful Spring Boot service

To test the increaseWins method, run the following two CURL command in a Bash shell:

$ curl -X POST "http://localhost:8080/score/wins"
$ curl -X GET "http://localhost:8080/score/"

The output of the second command is:

{ "wins":"1", "losses":"0", "ties": "0"}

Now trigger a PUT invocation, with query parameters being used to carry the payload:

$ curl -X PUT "http://localhost:8080/score?wins=31&losses=11&ties=22"

This results in an output of:

{ "wins":"31", "losses":"11", "ties": "22"}

And that’s it, a complete, step-by-step Spring Boot RESTful web services example that creates a fully functional Spring Boot application.

How to improve the RESTful Spring example

Now there is plenty of room for improvement and expansion when it comes to this step-by-step Spring Boot RESTful web services example.

Obviously, using the static variables in the Score class is a poor way to manage state, so at the very least we should offload the job of state management to a JavaBean with an ObjectOutputStream. And neither a JavaBeans or RESTful web service should be responsible for data persistence, so there will be opportunities to integrate Hibernate, JPA and Spring Boot web services. We could also invoke the Spring Boot RESTful web service example through a Spring MVC app or a Spring RestTemplate instead of CURL, and of course, it would be nice to package this app in an executable JAR file with an embedded Tomcat or embedded WebSphere Liberty server and deploy it as a microservice. But all of those things would complicate the example and distract from the core purpose, which is to demonstrate just how easy it is to develop a RESTful Spring web service using the Spring Boot framework.

These aforementioned issues will be addressed in subsequent tutorials. The source code for this step-by-step Spring Boot RESTful web services example can be found on GitHub.

Spring Boot and Embedded Servers – Tomcat, Jetty and Undertow

http://www.springboottutorial.com/spring-boot-with-embedded-servers-tomcat-jetty

 


This guide will help you understand why embedded servers are gaining popularity. We will discuss the different options that Spring Boot supports – Tomcat, Jetty and Undertow.

You will learn

  • What is an embedded server?
  • Why are embedded servers getting popular?
  • What are the different embedded servers that Spring Boot supports?
  • How do you switch from one embedded server to another?

What is an Embedded Server?

Think about what you would need to be able to deploy your application (typically) on a virtual machine.

  • Step 1 : Install Java
  • Step 2 : Install the Web/Application Server (Tomcat/Websphere/Weblogic etc)
  • Step 3 : Deploy the application war

What if we want to simplify this?

How about making the server a part of the application?

You would just need a virtual machine with Java installed and you would be able to directly deploy the application on the virtual machine. Isn’t it cool?

This idea is the genesis for Embedded Servers.

When we create an application deployable, we would embed the server (for example, tomcat) inside the deployable.

For example, for a Spring Boot Application, you can generate an application jar which contains Embedded Tomcat. You can run a web application as a normal Java application!

Embedded server implies that our deployable unit contains the binaries for the server (example, tomcat.jar).

Creating an Embedded Server Project with Spring Initializr

Spring Initializr http://start.spring.io/ is great tool to bootstrap your Spring Boot projects.

Image

As shown in the image above, following steps have to be done

  • Launch Spring Initializr and choose the following
    • Choose com.in28minutes.springboot.tutorial.basics.example as Group
    • Choose spring-boot-tutorial-basics as Artifact
    • Choose following dependencies
      • Web
      • DevTools
  • Click Generate Project.
  • Import the project into Eclipse. File -> Import -> Existing Maven Project.

Default Embedded Server with Spring Boot – Tomcat

We have included Spring Boot Starter Web in our dependencies when creating the spring boot project.

Let’s take a quick look at the dependencies for spring-boot-starter-web

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-tomcat</artifactId>
  <version>2.0.0.RELEASE</version>
  <scope>compile</scope>
</dependency>

You can see that by default Starter Web includes a dependency on starter tomcat.

Starter Tomcat has the following dependencies.

<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-core</artifactId>
  <version>8.5.23</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-el</artifactId>
  <version>8.5.23</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-websocket</artifactId>
  <version>8.5.23</version>
  <scope>compile</scope>
</dependency>

Starter Tomcat brings in all the dependencies need to run Tomcat as an embedded server.

Run the web application using an Embedded Server

When you run SpringBootTutorialBasicsApplication.java as a Java Application, you would see that the server would start up and start serving requests.

An extract from the log

o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)

You can see that tomcat has started by default on port 8080.

You can customize the port in application.properties

server.port=9080

When you do a ‘mvn clean install’ on the project, a jar artifact named spring-boot-tutorial-basics-0.0.1-SNAPSHOT.jar is generated.

This jar can be used to run the application on any machine where Java 8 is installed.

The tomcat embedded server is also packaged inside this jar

Using Jetty as Embedded Server with Spring Boot

Remove the existing dependency on spring-boot-starter-web and add these in.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Using Undertow as Embedded Server with Spring Boot

Remove the existing dependency on spring-boot-starter-web and add these in.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

Embedded Server Spring Boot Configuration

Spring Boot provides a number of options to configure the embedded server through application.properties

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.compression.enabled=false # If response compression is enabled.
server.context-path= # Context path of the application.
server.display-name=application # Display name of the application.
server.error.include-stacktrace=never # When to include a "stacktrace" attribute.
server.error.path=/error # Path of the error controller.
server.error.whitelabel.enabled=true # Enable the default error page displayed in browsers in case of a server error.
server.port=8080 # Server HTTP port.
server.server-header= # Value to use for the Server response header (no header is sent if empty)
server.servlet-path=/ # Path of the main dispatcher servlet.

Here are a few Jetty specific options

server.jetty.acceptors= # Number of acceptor threads to use.
server.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content.
server.jetty.selectors= # Number of selector threads to use.

You can also configure ssl on the embedded server

server.ssl.ciphers= # Supported SSL ciphers.
server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store.
server.ssl.enabled= # Enable SSL support.
server.ssl.enabled-protocols= # Enabled SSL protocols.
server.ssl.key-alias= # Alias that identifies the key in the key store.
server.ssl.key-password= # Password used to access the key in the key store.
server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file).
server.ssl.key-store-password= # Password used to access the key store.
server.ssl.key-store-provider= # Provider for the key store.
server.ssl.key-store-type= # Type of the key store.
server.ssl.protocol=TLS # SSL protocol to use.
server.ssl.trust-store= # Trust store that holds SSL certificates.
server.ssl.trust-store-password= # Password used to access the trust store.
server.ssl.trust-store-provider= # Provider for the trust store.
server.ssl.trust-store-type= # Type of the trust store.

A few tomcat specific properties are listed below

server.tomcat.accept-count= # Maximum queue length for incoming connection requests when all possible request processing threads are in use.
server.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be relative to the tomcat base dir or absolute.
server.tomcat.accesslog.enabled=false # Enable access log.
server.tomcat.basedir= # Tomcat base directory. If not specified a temporary directory will be used.
server.tomcat.max-connections= # Maximum number of connections that the server will accept and process at any given time.
server.tomcat.max-threads=0 # Maximum amount of worker threads.
server.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI.

For complete list options refer spring documentation – https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Tutorial: Use Spring Boot to Build and Deploy WAR Files

https://stormpath.com/blog/tutorial-spring-boot-war-files

Spring Boot makes it easy to create stand-alone Java web applications. However in production environments, a web container often already exists. How do we deploy our apps in these situations and have them run side-by-side with other servlets? In this tutorial, we’ll walk through how to use WAR files to do just that.

Getting Started with With Spring Boot, Tomcat, and WAR Files

In a previous tutorial, we built a simple RESTful web app using Spring Boot. I’m going to use this as a base and show how to deploy it into a container. You can grab the code for this tutorial on GitHub.

To ensure an existing Spring Boot app is container-ready one needs do three things
– Renaming the embedded Tomcat libraries
– Repackage the output file as a WAR
– Wire the application up as a servlet

Tomcat Libraries

Building a Spring Boot application produces a runnable jar file by default. If your app includes server functionality, then Tomcat will be bundled with it. We need to ensure the Tomcat libraries don’t clash with an existing container (since the container will include the same libraries).

When we do a clean clone of our repo (grab the code on GitHub if you haven’t yet) and do an mvn clean package we end up with a target directory containing our runnable jar.

This jar contains Tomcat libraries. To confirm this, we can rename it to .zip and look at the lib directory.
LIB Tomcat

You’ll see various .jar files starting with tomcat-. Some of these will clash with a running instance of Tomcat. We need to tell Spring Boot to move them.

To WAR! AKA: Build Your WAR Files

First, we must tell Spring Boot we want a WAR file as output. This is as easy as adding one line to our pom.xml.

Now when we build the package with

we will see a .war file inside our target directory:
WAR file in target directory

As before we can rename the file to .zip to see what’s inside. Everything is basically the same, just slightly re-ordered. Now lib is inside of WEB-INF anddemo` (where our project code sits) is in WEB-INF/classes.
Web INF Files

Renaming Tomcat

Next, we tell Spring Boot to move our Tomcat libraries out of this folder. In our previous pom.xml we included three dependencies for our project – one for REST, one for data access, and another for the database.

Now we append the Spring Boot Tomcat Starter to this (which links to the Tomcat libraries you need when embedding) and set the scope of the dependency to provided.

This will still include the .jar files as before but will put them in a new folder called lib-provided.

We can see this if we follow the same procedure as before. Once we mvn clean package and rename our .war to .zip we’ll see inside WEB-INF the new folder has appeared. Inside are all the embedded Tomcat libraries (and you’ll see they are no longer in lib).
Embedded Tomcat Libraries

Now our application will happily reside in a servlet container without clashing with its libraries.

Setting Up a Servlet

The only other thing we need to do is wire our application up to start as a servlet. And to do this we need to modify our application definition.

In the REST app mentioned our Application.java used the SpringBootApplication annotation on the main class and defined a main method.

To set the app up as a servlet we extend the main class with SpringBootServletInitializer and override the configure method using SpringApplicationBuilder.

And that’s it! This application will now happily run inside a Tomcat container!

Installing Tomcat

Deploying WAR files to Tomcat is as easy as copying the file to Tomcat’s webapps directory. But first, you need to install Tomcat. On Ubuntu, you can use apt-get.

This will install and start the server automatically on port 8080.

On Windows it’s just as easy – download and extract the binary distribution .zip file and run startup.bat in the bin directory. This will open up a console window showing the output of Catalina.
Tomcat Console

In both cases, you can check to see if everything is running by browsing to localhost:8080. You should see the Tomcat default homepage.
Tomcat

(Who knew Tomcat was so easy to use?!)

Copy the WAR File

The last step is copying the WAR to webapps. Here the name is important – whatever filename we choose will be used to map HTTP requests to our application. (All done automatically! I think this is amazing.) In an attempt to be more URL-friendly, I’m going to use demo.war.

On Ubuntu, this can be done with:

In Windows, use Explorer for the copy and then wait for the console window to show deployment messages.
WAR Deployment Message

And that’s it! Just by copying one file across our app is automatically booted and running side-by-side with the default Tomcat servlet.

Test Your WAR File Deployment

As before we test this by making calls using curl. Normally we called get on localhost but now our application is mapped to /demo/.

This shows you available URLs. To see what people objects are available you can use:

Or, create new ones with:

Note: In my testing I found the deploy on Windows to be somewhat brittle. Sometimes I needed to close and rerun startup.bat.

Run as a Standalone Application

One last thing – because our Tomcat libraries are still there (just moved) we are able to run this application on it’s own. So mvn spring-boot:run still works !

DEPLOY A SPRING BOOT APP ON YOUR OWN SERVER…

https://www.theguild.nl/deploy-a-spring-boot-app-on-your-own-server-in-less-than-15-minutes/

 

Hosted PaaS (Platform As A Service) offerings like Heroku and OpenShift are great but not always suitable or even possible to use. If you need or want full control over your data and servers, or you just want to host your latest side project but don’t want Heroku dyno sleeping you might just want to self host.

Traditionally self-hosting was painful and cumbersome but today there are plenty options to self-host your apps that are nearly as painless as a hosted PaaS solution. In this tutorial I will show you how to deploy an app on Dokku:

Dokku is an extensible, open source Platform as a Service that runs on a single server of your choice.

Dokku provides an environment very similar to Heroku technically, allowing Dokku to take advantage of Heroku buildpacks to deploy your apps. Dokku uses these buildpacks to automatically build Docker containers that can run your apps and services. Refer to the Dokku documentation for more information on Dokku.

For this tutorial we’ll be using this Spring Boot example app I’ve set up. It’s a very basic app with a single HTTP endpoint that serves up a semi-random quote retrieved from a Postgres database. It’s a completely vanilla Spring Boot app, except for a single file to instruct Dokku how to start the app but more on that later. Let’s get started!

1. GET A (VIRTUAL) SERVER

Get a server with root access. Dokku requires at least 1GB of RAM and officially only supports Ubuntu 14.04 x64.

For convenience you’ll want to assign a DNS hostname (dokku.example.org) to your servers IP and preferably even assign a wildcard record so you can deploy apps on <app name>.dokku.example.org.

2. INSTALL DOKKU

SSH into your server and execute the following command to kick off the Dokku installation. Run this either as root or make sure your user account has sudo permissions.

1
wget -qO- https://raw.githubusercontent.com/dokku/dokku/v0.4.14/bootstrap.sh | bash

Sit back, get some coffee, this will take a couple of minutes. When the command completes open your browser and navigate to the ip address or hostname assigned to your server to complete the Dokku setup.

Dokku setup

Provide your SSH public key here so you’ll be able to push your app to Dokku later via Git. Enable use virtualhost naming for apps and enter the hostname you assigned to your server in step 1.

That’s it, you now have a fully functional Dokku instance up and running! Let’s see what it takes to actually deploy an app.

3. PREPARE YOUR APP FOR DEPLOYMENT ON DOKKU

We’re about ready to deploy our first app. In general if you want to deploy an app on Dokku you don’t need to make a lot of modifications to your app. Especially if your app adheres to the Twelve Factor guidelines you should be fine. Most importantly your app should allow configuration via environment variables or command line parameters.

Fortunately Spring Boot embraces the Twelve Factor guidelines. Spring Boot supports configuration via environment variables out of the box and it’s trivial to implement your own.

Looking at the example app I prepared there are two important things to notice:

1. I’ve created two property aliases to allow configuration via $PORT and $DATABASE_URL. This is not strictly necessary but I prefer the more generic environment variables over the Spring specific ones.

1
2
3
// application.properties
spring.datasource.url=${database.url:jdbc:postgresql://localhost:5432/dokku-demo}
server.port=${port:8080}

2. I’ve added a Procfile to instruct Dokku how to start our app. Dokku will read this file during deployment and use the web process to boot our app. You can read more about Procfiles here.

1
2
# Procfile
web: env DATABASE_URL=$JDBC_DATABASE_URL target/dokku-boot-demo-0.0.1-SNAPSHOT.jar

During deployment Dokku invokes mvn install on our app so it will build a jar. Here we instruct Dokku that to launch our app it needs to execute the jar. We set the $DATABASE_URL to $JDBC_DATABASE_URLwhich is an environment variable provided by the Java buildpack that formats the database connection string for JDBC compatibility.

4. DEPLOY YOUR APP

Alright so now our app is Dokku compatible. Before we can push our app to Dokku we need to configure our application in Dokku. For simplicity enter the following dokku commands in an SSH session on your server. Later you can setup the Dokku CLI client to run these commands directly from your local machine.

First we’ll create our app in Dokku:

1
$ dokku apps:create my-app

Next we’ll install the Dokku Postgres plugin:

1
$ dokku plugin:install https://github.com/dokku/dokku-postgres.git postgres

This will pull in a Postgres Docker image so give it some time to complete.

Next create a Postgres instance for our app:

1
$ dokku postgres:create my-app-postgres

Link it to our app:

1
$ dokku postgres:link my-app-postgres my-app

That’s all the configuration we need, let’s actually deploy our app now!

First clone the example app to your local machine:

1
2
$ git clone https://github.com/kabisa/dokku-boot-demo.git
$ cd dokku-boot-demo

Dokku uses a Git push to deploy model, meaning that you push your app sources into Dokku using Git. To deploy you simply add a git remote to your repository pointing to Dokku and git push every time you want to deploy your latest changes.

Execute the following command in your shell. Replace dokku.example.org with your actual Dokku hostname.

1
$ git remote add dokku dokku@dokku.example.org:my-app

And finally push our app to Dokku:

1
$ git push dokku master

Dokku will now detect our app is a Java app, build a Docker image suitable to run Java apps, compile the app and run it.

You should see similar output as below:

Dokku deploy gif

Open your browser at http://my-app.dokku.example.org/ and see a nice random quote!

CLOSING THOUGHTS

Dokku takes a bit of one time setup but once you have your Dokku instance ready, deploying new applications will be a breeze. Do note that Dokku was designed for simple single server setups. If you need fancy stuff like clustering, access control etc you might want to look at one of the more comprehensive projects in this space like FlynnDeis or Cloud Foundry.

Even though Dokku is quite simple, we’ve only scratched the surface of what it can do. You now have a fully functional Dokku instance so go ahead and explore the Dokku docs to see what more is possible!

If there’s no suitable Heroku buildpack for your app you can always deploy a raw Docker container using Dokku by simply including a Dockerfile in the root of your project.

If you’re planning to deploy a more complex Spring Boot app to Dokku you might want to look into Spring Cloud Connectors. Spring Cloud Connectors can automatically detect that you’re running in a cloud platform, and configure your HTTP port and database automatically for you. Spring Cloud Connectors officially don’t support Dokku, but the Heroku support works just fine with Dokku.

Also be sure to check out the plugins that Dokku offers to make use of databases, message brokers etc. There’s even a Dokku Let’s Encrypt plugin for dead easy Let’s Encrypt SSL certificates.

Happy deploying!

Me 2016 square

PASCAL WIDDERSHOVEN

Full Stack Developer • Github: pascalw • Twitter: @_pascalw

Spring ORM example – JPA, Hibernate, Transaction

Welcome to the Spring ORM Example Tutorial. Today we will look into Spring ORM example using Hibernate JPA transaction management. I will show you a very simple example of Spring standalone application with following features.
  • Dependency Injection (@Autowired annotation)
  • JPA EntityManager (provided by Hibernate)
  • Annotated transactional methods (@Transactional annotation)

Spring ORM Example

spring orm example, spring orm, spring jpa hibernate example, spring hibernate transaction management, spring hibernate jpa

I have used in-memory database for Spring ORM example, so no need for any database setup (but you can change it to any other database in the spring.xml datasource section). This is a Spring ORM standalone application to minimize all dependencies (but you can easily change it to a web project by configuration if you get familiar with spring).

NOTE: For Spring AOP based Transactional (without @Transactional annotation) method resolution approach please check this tutorial: Spring ORM AOP Transaction Management.

Below image shows our final Spring ORM example project.

Spring ORM, Spring ORM Example, Spring ORM JPA Hibernate

 

Let’s go through each of the Spring ORM example project components one by one.

Spring ORM Maven dependencies

Below is our final pom.xml file having Spring ORM dependencies. We have used Spring 4 and Hibernate 4 in our Spring ORM example.

  • We need spring-context and spring-orm as Spring dependencies.
  • We use hibernate-entitymanager for Hibernate as JPA implementation. hibernate-entitymanager is dependent on hibernate-core this why we don’t have to put hibernate-core in pom.xml explicitly. It’s being pulled into our project through maven transitive dependencies.
  • We also need JDBC driver as dependency for database access. We are using HSQLDB that contains the JDBC driver and a working in memory database.

Spring ORM Model Class

We can use standard JPA annotations for mapping in our model beans because Hibernate provides JPA implementation.

We use @Entity and @Id JPA annotations to qualify our POJO as an Entity and to define it’s primary key.

Spring ORM DAO Class

We create a very simple DAO class that provides persist and findALL methods.

  • @Component is Spring annotation that tell the Spring container that we can use this class through Spring IoC (Dependency Injection).
  • We use JPA @PersistenceContext annotation that indicate dependency injection to an EntityManager. Spring injects a proper instance of EntityManager according to the spring.xml configuration.

Spring ORM Service Class

Our simple service class has 2 write and 1 read methods – add, addAll and listAll.

 

  • We use Spring @Autowired annotation to inject ProductDao in our service class.
  • We want to use transaction management, so methods are annotated with @Transactional Spring annotation. The listAll method only reads the database so we set the @Transactional annotation to read-only for optimisation.

Spring ORM Example Bean Configuration XML

Our spring ORM example project java classes are ready, let’s look at our spring bean configuration file now.

spring.xml

  1. First we tell spring that we want to use classpath scanning for Spring components (Services, DAOs) rather than defining them one by one in spring xml. We have also enabled Spring annotation detection.
  2. Adding the datasource, that is currently HSQLDB in-memory database.
  3. We set up a JPA EntityManagerFactory that will used by the application to obtain an EntityManager. Spring supports 3 different ways to do this, we have used LocalContainerEntityManagerFactoryBean for full JPA capabilities.We set LocalContainerEntityManagerFactoryBean attributes as:
    1. packagesToScan attribute that points to our model classes package.
    2. datasource defined earlier in spring configuration file.
    3. jpaVendorAdapter as Hibernate and setting some hibernate properties.
  4. We create Spring PlatformTransactionManager instance as a JpaTransactionManager. This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
  5. We enable the configuration of transactional behavior based on annotations, and we set the transactionManager we created.

Spring ORM Hibernate JPA Example Test Program

Our spring ORM JPA Hibernate example project is ready, so let’s write a test program for our application.

You can see how easily we can start the Spring container from a main method. We are getting our first dependency injected entry point, the service class instance. ProductDao class reference injected to the ProductService class after the spring context is initialized.

After we got ProducService instance, we can test it’s methods, all method call will be transactional due to Spring’s proxy mechanism. We also test rollback in this example.

If you run above spring ORM example test program, you will get below logs.

Note that the second transaction is rolled back, this why product list didn’t changed.

If you use log4j.properties file from attached source, you can see what’s going on under the hood.

References:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html

You can download the final Spring ORM JPA Hibernate Example project from below link and play around with it to learn more.

Show Buttons
Hide Buttons