Back Home

Hot Swapping

http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html

properly configured with the template cache disabled springboot is capable of quite acceptable hotswapping of resouces.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.5.RELEASE")
        classpath 'org.springframework:springloaded:1.2.6.RELEASE'

    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-serving-web-content'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    compile("org.springframework.boot:spring-boot-devtools")
    testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

springBoot {
    mainClass="hello.Application"
}

bootRun {
    addResources = true
}

idea {
    module {
        inheritOutputDirs = false
        outputDir = file("$buildDir/classes/main/")
    }
}

SpringBoot Web

WebJars

While the nodejs community keeps spinning out tools for dependency managment including npm, bower, grunt-ish and now yarn. There is pretty simple maven, gradle integration for front end components with webjars

A middle ground is to extract the webjars (much like bower) to an asset directory (they can be webpacked afterwards) Jbake has a nice gradle unpack script at https://github.com/aruizca/ajaxanywhere-site/blob/master/build.gradle

Spring Properties

Using external Json Properties:

@PropertySource(value = { "classpath:/app_config.json" }, factory=Application.JsonLoader.class )
public class Application {
 
  public static class JsonLoader implements PropertySourceFactory {
        @Override
        public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
            return new MapPropertySource("json-source", readValue);
        }
 
    }

this converts a property into a dot notation and properties can be instantiated

    @Value( "${db_table}" )
    private String TABLE_NAME;

However passing the envrionment variables around can be problematic and what appears safer for components is to

// in the main class 
  @Autowired
  private Environment env;
 
  add Environemnt to the constructor of the other components 
 
   public  DynamoDbHelper(Environment env) {
        TABLE_NAME =  env.getProperty("db_table");
        logger.info("connecting to dynamodb " +  TABLE_NAME );
        }
 

SpringBoot Profiles

Spring also provides an “profile” configuration it switch property files (or code) between environments nv The spring boot environment property can be passed via a property parameter

-Dspring.profiles.active=dev

This will then pickup the appropriate property file:

application.properties        // the default properties 
application-dev.properties    // if profile is dev 

for code configuration one can use the @Profile property .e.g

@Component
@Profile("production")
//my production code verison 

For remote (cloud) configuration see the Spring Cloud config

Spring Boot Stats

Telegraf meets your requirements. It pulls data from jolokia and save to InfluxDB.

All you need to do is enable actuator and jolokia for SpringbootApplication, it is easy to add dependency to your maven:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jolokia</groupId>
        <artifactId>jolokia-core</artifactId>
    </dependency>

After this you need configure telegraf to connect your web server and influxDB, here is an example config:

[tags]
dc = "local-1"

[agent]
interval = "10s"

[[inputs.jolokia]]
context = "/jolokia"

[[inputs.jolokia.servers]]
name = "catalog"
host = "{web server ip address}"
port = "{web server port}"

[[inputs.jolokia.metrics]]
name = "metrics"
mbean  = "org.springframework.boot:name=metricsEndpoint,type=Endpoint"
attribute = "Data"

[outputs]
[outputs.influxdb]
url = "{http://influxdb:port}"
database = "telegraf"
precision = "s"

Make sure network of upper configuration is available, then you will get data in you influxDB.

Configure grafana to display the data stored in influxDB:

  • Add a influxDB type datasource
  • Create a new Dashboard and Graph panel.
  • Configure Graph panel and choose which filed you want to display in Metrics setting.
  • You will see the data on the panel.

SpringBoot Swagger

Swagger now branded as part of OpenAPI Specification provides to the means to edit and generate RESTful contract for your API, detailing all of its resources and operations in a human and machine readable format for easy development, discovery, and integration.

To round trip the api definition we

  • Workshop the swagger in the swagger editor
  • Generate the swagger springboot interface
  • modify and expose the springboot definition
  • test the api definition

Additionally the can the traditional jaxrs annotations be expose by spring boot swagger

The Swagger Editor is available as a git nodejs project. Alternativly it can be run as a docker project swagger-editor runs on port 8080 and can be exposed to your prefered port via the usual docker mapping.

 
sudo docker pull swaggerapi/swagger-editor
sudo docker run -d -p 8094:8080 swaggerapi/swagger-editor

This will open the default petstore example

See my swagger documentation for creating the api

SpringCloud

Spring Cloud takes a very declarative approach, and often you get a lot of fetaures with just a classpath change and/or an annotation. Example application that is a discovery client:

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

Main Projects

Spring Data

Overview of Persisance with Spring including:

Spring JDBC provides templates for reducing boilerplate code for accessing a database through plain old way - you write your own SQL queries.

Spring-ORM provides simplified templates for accessing databases through ORM technologies, such as Hibernate, My(i)Batis etc. When executing jdbc .. one can use standard try/catch on a transaction error or

Spring boot provides transaction annotation on a method

public class UserRepository {
 
    @Transactional(noRollbackFor=DuplicateEmailException.class)
    public User createUser(){
        //if user exist, throw DuplicateEmailException
    }
}
 
void registerUser(User user) {
    try {
       userRepository.create(user);
    catch(DuplicateEmailException e) {
       User registeredUser = userRepository.findByEmail(user.getEmail());
       mailService.sendAlreadyRegisteredEmail(registeredUser);
    }
}

Spring Data DynamoDb

Spring Integration

The Spring Integration home page

There are a number of major extensions:

    • Amazon Simple Email Service (SES)
    • Amazon Simple Storage Service (S3)
    • Amazon Simple Queue Service (SQS)
    • Amazon Simple Notification Service (SNS)
    • Amazon DynamoDB (Analysis ongoing)
    • Amazon SimpleDB (Not initiated)

Spring Data Elastic

Spring Batch and Retry

//import the necessary classes
import org.springframework.batch.retry.RetryCallback;
import org.springframework.batch.retry.RetryContext;
import org.springframework.batch.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.batch.retry.policy.SimpleRetryPolicy;
import org.springframework.batch.retry.support.RetryTemplate;
...
 
// create the retry template
final RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new SimpleRetryPolicy(5));
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(1000L);
template.setBackOffPolicy(backOffPolicy);
 
// execute the operation using the retry template
template.execute(new RetryCallback<Remote>() {
  @Override
  public Remote doWithRetry(final RetryContext context) throws Exception {
    return (Remote) Naming.lookup("rmi://somehost:2106/MyApp");
  }
});

Spring Cloud Config

Features

  • Distributed/versioned configuration
  • Service registration and discovery
  • Routing
  • Service-to-service calls
  • Load balancing
  • Circuit Breakers
  • Global locks
  • Leadership election and cluster state
  • Distributed messaging

* Centralized external configuration management backed by a git repository. The configuration resources map directly to Spring `Environment` but could be used by non-Spring applications if desired.

  • Integrates Spring Cloud Netflix - Integration with various Netflix OSS components (Eureka, Hystrix, Zuul, Archaius, etc.).

Spring Cloud Data Flow

Spring Cloud Data Flow is a toolkit for building data integration and real-time data processing pipelines.

Spring 5 WebFlux

Based on Reactor

 
springboot.txt · Last modified: 2018/05/14 10:21 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd