Wednesday, September 20, 2017

java jdbc - how to connect to oracle using service name instead of sid

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

Tuesday, September 19, 2017

multiple jdbc instance

@Configuration
public class DatabaseConfig {

    @Bean(name = "dsSlave")
    @ConfigurationProperties(prefix="spring.mysql_slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dsMaster")
    @Primary
    @ConfigurationProperties(prefix="spring.mysql_master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

   @Bean(name = "jdbcSlave")
@Autowired
public JdbcTemplate slaveJdbcTemplate(@Qualifier("dsSlave") DataSource dsSlave) {
    return new JdbcTemplate(dsSlave);
}

    @Bean(name = "jdbcMaster")
    @Autowired
    public JdbcTemplate masterJdbcTemplate(@Qualifier("dsMaster")DataSource dsMaster) {
        return new JdbcTemplate(dsMaster);
    }

}




@Component
public class SqlService {

    @Autowired
    @Qualifier("jdbcSlave")
    private JdbcTemplate jdbcTemplate;

    public String getHelloMessage() {
        String host = jdbcTemplate.queryForObject("select @@hostname;", String.class);
        System.out.println(host);
        return "Hello";
    }

}

Saturday, September 9, 2017

Zuul Filter


PRE: Filters execute before routing to the origin. For example: request authentication, logging debug info
ROUTING: Filters handle routing the request to an origin.
POST: Filters execute after the request has been routed to the origin.
ERROR: Filters execute when an error occurs during one of the other phases.


package org.springframework.cloud.samplezuulfilters;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;

@EnableZuulProxy
@SpringBootApplication
public class ZuulGatewayApplication {

@Bean
public AddResponseHeaderFilter addResponseHeaderFilter() {
return new AddResponseHeaderFilter();
}

@Bean
public ModifyResponseBodyFilter modifyResponseHeaderFilter() {
return new ModifyResponseBodyFilter();
}

@Bean
public ModifyResponseDataStreamFilter modifyResponseDataStreamFilter() {
return new ModifyResponseDataStreamFilter();
}

@Bean
public PrefixRequestEntityFilter prefixRequestEntityFilter() {
return new PrefixRequestEntityFilter();
}

@Bean
public QueryParamPortPreFilter queryParamPortPreFilter() {
return new QueryParamPortPreFilter();
}

@Bean
public QueryParamServiceIdPreFilter queryParamServiceIdPreFilter() {
return new QueryParamServiceIdPreFilter();
}

@Bean
public UppercaseRequestEntityFilter modifyRequestEntityFilter() {
return new UppercaseRequestEntityFilter();
}

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

--------------------------

package org.springframework.cloud.samplezuulfilters;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import com.netflix.zuul.ZuulFilter;
import org.springframework.util.StreamUtils;

import com.netflix.zuul.context.RequestContext;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;
import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;

/**
 * @author Spencer Gibb
 */
public class UppercaseRequestEntityFilter extends ZuulFilter {
public String filterType() {
return "pre";
}

public int filterOrder() {
return 6;
}

public boolean shouldFilter() {
RequestContext context = getCurrentContext();
return context.getRequest().getParameter("service") == null;
}

public Object run() {
try {
RequestContext context = getCurrentContext();
InputStream in = (InputStream) context.get("requestEntity");
if (in == null) {
in = context.getRequest().getInputStream();
}
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
// body = "request body modified via set('requestEntity'): "+ body;
body = body.toUpperCase();
context.set("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
}
catch (IOException e) {
rethrowRuntimeException(e);
}
return null;
}
}

----------------------------

package org.springframework.cloud.samplezuulfilters;

import javax.servlet.http.HttpServletRequest;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;

/**
 * @author Spencer Gibb
 */
public class QueryParamServiceIdPreFilter extends ZuulFilter {

public int filterOrder() {
// run before PreDecorationFilter
return 5 - 1;
}

public String filterType() {
return "pre";
}

@Override
public boolean shouldFilter() {
RequestContext ctx = getCurrentContext();
return ctx.getRequest().getParameter("service") != null;
}

public Object run() {
RequestContext ctx = getCurrentContext();
HttpServletRequest request = ctx.getRequest();
// put the serviceId in `RequestContext`
ctx.put("serviceId", request.getParameter("service"));
return null;
}
}

----------------------------------------

package org.springframework.cloud.samplezuulfilters;

import javax.servlet.http.HttpServletRequest;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;

/**
 * @author Spencer Gibb
 */
public class QueryParamPortPreFilter extends ZuulFilter {

public int filterOrder() {
// run after PreDecorationFilter
return 5 + 1;
}

public String filterType() {
return "pre";
}

@Override
public boolean shouldFilter() {
RequestContext ctx = getCurrentContext();
return ctx.getRequest().getParameter("port") != null;
}

public Object run() {
RequestContext ctx = getCurrentContext();
HttpServletRequest request = ctx.getRequest();
// put the serviceId in `RequestContext`
String port = request.getParameter("port");
try {
URL url = UriComponentsBuilder.fromUri(ctx.getRouteHost().toURI())
.port(new Integer(port))
.build().toUri().toURL();
ctx.setRouteHost(url);
} catch (Exception e) {
ReflectionUtils.rethrowRuntimeException(e);
}
return null;
}
}

----------------------------------------

package org.springframework.cloud.samplezuulfilters;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.util.StreamUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.ServletInputStreamWrapper;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;
import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;

/**
 * @author Spencer Gibb
 */
public class PrefixRequestEntityFilter extends ZuulFilter {
public String filterType() {
return "pre";
}

public int filterOrder() {
return 6;
}

public boolean shouldFilter() {
RequestContext context = getCurrentContext();
return context.getRequest().getParameter("service") != null;
}

public Object run() {
try {
RequestContext context = getCurrentContext();
InputStream in = (InputStream) context.get("requestEntity");
if (in == null) {
in = context.getRequest().getInputStream();
}
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
body = "request body modified via request wrapper: "+ body;
byte[] bytes = body.getBytes("UTF-8");
context.setRequest(new HttpServletRequestWrapper(getCurrentContext().getRequest()) {
@Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStreamWrapper(bytes);
}

@Override
public int getContentLength() {
return bytes.length;
}

@Override
public long getContentLengthLong() {
return bytes.length;
}
});
}
catch (IOException e) {
rethrowRuntimeException(e);
}
return null;
}
}

----------------------------------

package org.springframework.cloud.samplezuulfilters;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.springframework.util.StreamUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;
import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;

/**
 * @author Spencer Gibb
 */
public class ModifyResponseDataStreamFilter extends ZuulFilter {
public String filterType() {
return "post";
}

public int filterOrder() {
return 999;
}

public boolean shouldFilter() {
RequestContext context = getCurrentContext();
return context.getRequest().getParameter("service") != null;
}

public Object run() {
try {
RequestContext context = getCurrentContext();
InputStream stream = context.getResponseDataStream();
String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
body = "Modified via setResponseDataStream(): " + body;
context.setResponseDataStream(new ByteArrayInputStream(body.getBytes("UTF-8")));
}
catch (IOException e) {
rethrowRuntimeException(e);
}
return null;
}
}

----------------------------------------

package org.springframework.cloud.samplezuulfilters;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.springframework.util.StreamUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;
import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;

/**
 * @author Spencer Gibb
 */
public class ModifyResponseBodyFilter extends ZuulFilter {
public String filterType() {
return "post";
}

public int filterOrder() {
return 999;
}

public boolean shouldFilter() {
RequestContext context = getCurrentContext();
return context.getRequest().getParameter("service") == null;
}

public Object run() {
try {
RequestContext context = getCurrentContext();
InputStream stream = context.getResponseDataStream();
String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
context.setResponseBody("Modified via setResponseBody(): "+body);
}
catch (IOException e) {
rethrowRuntimeException(e);
}
return null;
}
}

-----------------------

package org.springframework.cloud.samplezuulfilters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author Spencer Gibb
 */
public class AddResponseHeaderFilter extends ZuulFilter {
public String filterType() {
return "post";
}

public int filterOrder() {
return 999;
}

public boolean shouldFilter() {
return true;
}

public Object run() {
RequestContext context = RequestContext.getCurrentContext();
HttpServletResponse servletResponse = context.getResponse();
servletResponse.addHeader("X-Foo",
UUID.randomUUID().toString());
return null;
}
}
-------------------

public class RequestLoggerFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(RequestLoggerFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        log.info(String.format("%s request to %s", request.getMethod(),
                request.getRequestURL().toString()));

        return null;
    }

}

Study about zuul netflix

Zuul is a JVM based router and server side load balancer by Netflix.
It provides a single entry to our system, which allows a browser, mobile app, or other user interface to consume services from multiple hosts without managing cross-origin resource sharing (CORS) and authentication for each one. We can integrate Zuul with other Netflix projects like Hystrix for fault tolerance and Eureka for service discovery, or use it to manage routing rules, filters, and load balancing across your system.





Zuul is a JVM based router and server side load balancer by Netflix.

Zuul is the front door for all requests from devices and web sites to the backend of the Netflix streaming application. As an edge service application, Zuul is built to enable dynamic routing, monitoring, resiliency and security.

Routing in an integral part of a microservice architecture. For example, may be mapped to your web application, /api/users is mapped to the user service and /api/shop is mapped to the shop service. Zuul is a JVM based router and server side load balancer by Netflix.

(dependency)
    (groupId)org.springframework.cloud(/groupId)
    (artifactId)spring-cloud-starter-zuul(/artifactId)
    (version)1.0.4.RELEASE(/version)
(/dependency)

Netflix Zuul to Proxy your Microservices
=======================================
Netflix (a major adopter of microservices) created and open-sourced its Zuul proxy server. Zuul is an edge service that proxies requests to multiple backing services. It provides a unified “front door” to your system, which allows a browser, mobile app, or other user interface to consume services from multiple hosts without managing cross-origin resource sharing (CORS) and authentication for each one. You can integrate Zuul with other Netflix projects like Hystrix for fault tolerance and Eureka for service discovery, or use it to manage routing rules, filters, and load balancing across your system.

The configuration contains three named routes. Each route has a path, which defines the URL mapping in the Zuul server, and a url, which defines the URL of the remote service to proxy

Zuul has the ability to load-balance its services and failover to an alternative service if the primary host goes down.

Adding load balancing and failover
==================================
The Zuul server you deployed comes pre-packaged with Ribbon, a client-side load-balancer, and Hystrix, a fault tolerance library.

Example:
=======
zuul:
  routes:
    httpbin:
      path: /**
      serviceId: httpbin

httpbin:
  ribbon:
    listOfServers: httpbin.org,eu.httpbin.org

ribbon:
  eureka:
    enabled: false

Example2:
========
zuul:
  #Service will be mapped under the /api URI
  prefix: /api
  routes:
    hello-server-url:
      path: /server/**
      url: http://localhost:8071
    hello-server-eurekaId:
      path: /server1/Test/**
      url: HELLO-SERVER
    hello-client:
      path: /client/**
      serviceId: HELLO-CLIENT
    httpbin:
      path: /httpbin/**
      serviceId: httpbin

httpbin:
  ribbon:
    listOfServers: http://localhost:8071,http://localhost:8075

ribbon:
  eureka:
    enabled: false

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8070/eureka/
  instance:
    hostname: localhost

server:
  port: 8079

spring:
  application:
    name: zuul-service

# Increase the Hystrix timeout to 60s (for all)
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 60000

This configuration tells Zuul to forward all requests to the httpbin service, which is defined after the zuul entry. The httpbin entry defines the available servers: httpbin.org and its European counterpart, eu.httpbin.org. If the first host goes down, the proxy will failover to the second host. It also disables Eureka discovery for Ribbon because you don’t have a Eureka server.... yet.


Connecting to Eureka
====================
zuul:
  routes:
    my-service:
      path: /my-service/**
      serviceId: my-service

eureka:
  client:
    serviceUrl:
      defaultZone: ${EUREKA_URL:http://user:password@localhost:5000}/eureka/

The configuration defines a single service route, my-service, which uses a serviceId with the same name. But unlike the Ribbon configuration, you have not defined the my-service details in this file. Instead, Zuul will retrieve them from the Eureka server, which is configured under the eureka entry. It defines the Eureka server’s location at $EUREKA_URL and falls back to a localhost address if it’s not set.  

Spring Cloud- REST call using Netflix Feign Client

Feign is a java to http client binder inspired by Retrofit, JAXRS-2.0, and WebSocket. Feign's first goal was reducing the complexity of binding Denominator uniformly to http apis regardless of restfulness. Previous examples in the employee-consumer we consumed the REST services exposed by the employee-producer using REST Template


But we had to write a lot of code to perform following-
For Load balancing using Ribbon.
Getting the Service instance and then the Base URL.
Make use of the REST Template for consuming service.

@Controller
public class ConsumerControllerClient {

@Autowired
private LoadBalancerClient loadBalancer;

public void getEmployee() throws RestClientException, IOException {

ServiceInstance serviceInstance=loadBalancer.choose("employee-producer");

System.out.println(serviceInstance.getUri());

String baseUrl=serviceInstance.getUri().toString();

baseUrl=baseUrl+"/employee";

RestTemplate restTemplate = new RestTemplate();
ResponseEntity response=null;
try{
response=restTemplate.exchange(baseUrl,
HttpMethod.GET, getHeaders(),String.class);
}catch (Exception ex)
{
System.out.println(ex);
}
System.out.println(response.getBody());
}

================================================================


The previous code, there are chances of exceptions like NullPointer and is not optimal. We will see how the call is made much easier and cleaner using Netflix Feign. If the Netflix Ribbon dependency is also in the classpath, then Feign also takes care of load balancing by default.

(?xml version="1.0" encoding="UTF-8"?)
(project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")
(modelVersion)4.0.0(/modelVersion)

(groupId)com.javainuse(/groupId)
(artifactId)employee-consumer(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(packaging)jar(/packaging)

(parent)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-parent(/artifactId)
(version)1.4.1.RELEASE(/version)
(relativePath /) (!-- lookup parent from repository --)
(/parent)

(properties)
(project.build.sourceEncoding)UTF-8(/project.build.sourceEncoding)
(project.reporting.outputEncoding)UTF-8(/project.reporting.outputEncoding)
(java.version)1.8(/java.version)
(/properties)

(dependencies)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-web(/artifactId)
(/dependency)

(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-eureka(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-ribbon(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-feign(/artifactId)
(/dependency)


(/dependencies)

(dependencyManagement)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-dependencies(/artifactId)
(version)Camden.SR6(/version)
(type)pom(/type)
(scope)import(/scope)
(/dependency)
(/dependencies)
(/dependencyManagement)


(/project)

We next define a Feign Client by creating an interface with @FeignClient annotation. We also specify the name value as "employee-producer". This value is the name of the service registered using Eureka for discovery. We define the method call to be made to consume the REST service exposed by the employee-producer module.


package com.javainuse.services;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.javainuse.controllers.Employee;

@FeignClient(name="employee-producer")
public interface RemoteCallService {
@RequestMapping(method=RequestMethod.GET, value="/employee")
public Employee getData();

}


Next we autowire the RemoteCallService in the ConsumerControllerClient class. Then using it make the REST call. Load Balancing is automatically taken care by Feign Client.

package com.javainuse.controllers;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.client.RestClientException;

import com.javainuse.services.RemoteCallService;

@Controller
public class ConsumerControllerClient {

@Autowired
private RemoteCallService loadBalancer;

public void getEmployee() throws RestClientException, IOException {

try {
Employee emp = loadBalancer.getData();
System.out.println(emp.getEmpId());
} catch (Exception ex) {
System.out.println(ex);
}
}

}


package com.javainuse;

import java.io.IOException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestClientException;

import com.javainuse.controllers.ConsumerControllerClient;

@SpringBootApplication
@EnableFeignClients
public class SpringBootHelloWorldApplication {

public static void main(String[] args) throws RestClientException, IOException {
ApplicationContext ctx = SpringApplication.run(SpringBootHelloWorldApplication.class, args);

ConsumerControllerClient consumerControllerClient = ctx.getBean(ConsumerControllerClient.class);
System.out.println(consumerControllerClient);
consumerControllerClient.getEmployee();

}

@Bean
public ConsumerControllerClient consumerControllerClient() {
return new ConsumerControllerClient();
}
}


FeignClient - Load Balancer with Eureka

feign-eureka-hello-server
=========================

HelloServerApplication.java
===========================
package demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Spencer Gibb
 */
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class HelloServerApplication {
@Autowired
DiscoveryClient client;

@RequestMapping("/")
public String hello() {
ServiceInstance localInstance = client.getLocalServiceInstance();
return "Hello World: "+ localInstance.getServiceId()+":"+localInstance.getHost()+":"+localInstance.getPort();
}

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


application.yml
===============
spring:
  application:
    name: HelloServer

server:
  port: 7111

eureka:
  password: password
  client:
    serviceUrl:
      defaultZone: http://user:${eureka.password}@localhost:8761/eureka/
  instance:
    leaseRenewalIntervalInSeconds: 10
    metadataMap:
      instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}}


pom.xml
======
(?xml version="1.0" encoding="UTF-8"?)
(project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")
(modelVersion)4.0.0(/modelVersion)

(groupId)org.test(/groupId)
(artifactId)feign-eureka-hello-server(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(packaging)jar(/packaging)

(name)feign-eureka-hello-server(/name)
(description)Demo project for Spring Cloud(/description)

(parent)
(groupId)org.test(/groupId)
(artifactId)feign-eureka(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(relativePath)..(/relativePath) (!-- lookup parent from repository --)
(/parent)

(properties)
(project.build.sourceEncoding)UTF-8(/project.build.sourceEncoding)
(java.version)1.8(/java.version)
(/properties)

(dependencies)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-web(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-actuator(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-feign(/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-test(/artifactId)
(scope)test(/scope)
(/dependency)
(/dependencies)

(build)
(plugins)
(plugin)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-maven-plugin(/artifactId)
(/plugin)
(plugin)
(groupId)pl.project13.maven(/groupId)
(artifactId)git-commit-id-plugin(/artifactId)
(/plugin)
(plugin)
(!--skip deploy (this is just a test module) --)
(artifactId)maven-deploy-plugin(/artifactId)
(configuration)
(skip)true(/skip)
(/configuration)
(/plugin)
(/plugins)
(/build)

(/project)


-------------------------------------------------------------------------------------------------------------------------------------------------------
feign-eureka-hello-client
=========================
HelloClientApplication.java
===========================
package demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * @author Spencer Gibb
 */
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@EnableFeignClients
public class HelloClientApplication {
@Autowired
HelloClient client;

@RequestMapping("/")
public String hello() {
return client.hello();
}

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

@FeignClient("HelloServer")
interface HelloClient {
@RequestMapping(value = "/", method = GET)
String hello();
}
}


application.yml
===============
spring:
  application:
    name: HelloClient

server:
  port: 7211

eureka:
  password: password
  client:
    serviceUrl:
      defaultZone: http://user:${eureka.password}@localhost:8761/eureka/
  instance:
    leaseRenewalIntervalInSeconds: 10
    metadataMap:
      instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}}


endpoints:
  restart:
    enabled: true
  shutdown:
    enabled: true
  health:
    sensitive: false


pom.xml
=======
(?xml version="1.0" encoding="UTF-8"?)
(project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")
(modelVersion)4.0.0(/modelVersion)

(groupId)org.test(/groupId)
(artifactId)feign-eureka-hello-client(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(packaging)jar(/packaging)

(name)feign-eureka-hello-client(/name)
(description)Demo project for Spring Cloud(/description)

(parent)
(groupId)org.test(/groupId)
(artifactId)feign-eureka(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(relativePath)..(/relativePath) (!-- lookup parent from repository --)
(/parent)

(properties)
(project.build.sourceEncoding)UTF-8(/project.build.sourceEncoding)
(java.version)1.8(/java.version)
(/properties)

(dependencies)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-web(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-actuator(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-feign(/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-test(/artifactId)
(scope)test(/scope)
(/dependency)
(/dependencies)

(build)
(plugins)
(plugin)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-maven-plugin(/artifactId)
(/plugin)
(plugin)
(groupId)pl.project13.maven(/groupId)
(artifactId)git-commit-id-plugin(/artifactId)
(/plugin)
(plugin)
(!--skip deploy (this is just a test module) --)
(artifactId)maven-deploy-plugin(/artifactId)
(configuration)
(skip)true(/skip)
(/configuration)
(/plugin)
(/plugins)
(/build)
(/project)


Testing:


When we call http://localhost:7211 one of the following messages will be shown: Hello World: HelloServer:192.168.0.14:7112

Hello World: HelloServer:192.168.0.14:7111

Ribbon - Load Balancer without Eureka

Ribbon is a client side load balancer, which gives you a lot of control over the behavior of HTTP and TCP clients. Ribbon's Client component offers a good set of configuration options such as connection timeouts, retries, retry algorithm (exponential, bounded back off) etc. Ribbon comes built in with a pluggable and customizable Load Balancing component.
Some of the load balancing strategies offered are listed below:

Simple Round Robin LB
Weighted Response Time LB
Zone Aware Round Robin LB
Random LB


Using Ribbon - Code:


@SpringBootApplication
@RestController
@RibbonClient(name = "hello-service", configuration = HelloServiceConfiguration.class)
public class UserApplication {
    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("/hi")
    public String hi(@RequestParam(value = "name", defaultValue = "Rafael") String name) {
        String greeting = this.restTemplate.getForObject("http://hello-service/greeting", String.class);
        return String.format("%s, %s!", greeting, name);
    }
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}
public class HelloServiceConfiguration {
    @Autowired
    IClientConfig ribbonClientConfig;
    @Bean
    public IPing ribbonPing(IClientConfig config) {
        return new PingUrl();
    }
    @Bean
    public IRule ribbonRule(IClientConfig config) {
        return new AvailabilityFilteringRule();
    }
}


spring:
  application:
    name: user-service
server:
  port: 8888
hello-service:
  ribbon:
    eureka:
      enabled: false
    listOfServers: localhost:8090,localhost:9092,localhost:9999
    ServerListRefreshInterval: 15000



------------------------

@RibbonClient(name = "myClient", configuration = MyConfiguration.class)

@Configuration
public class MyConfiguration {
  @Bean
  public IRule ribbonRule() {
    return new RoundRobinRule();
  }
}

Load Balancing



 Load Balancing automatically distributes incoming application traffic between two or more computers.

 It enables you to achieve fault tolerance in your applications, seamlessly providing the required amount of load balancing capacity needed to route application traffic.

 Load balancing aims to optimize resource use, maximize throughput, minimize response time, and avoid overload of any single resource.

Using multiple components with load balancing instead of a single component may increase reliability and availability through redundancy.

Eureka Properties





eureka.environment
The environment name in which this Eureka cluster is running (dev, staging, prod).

eureka.datacenter
The datacenter in which this instance is running.

eureka.enableSelfPreservation
Specifies if this instance should enter Self Preservation Mode in case it cannot contact Eureka servers to refresh its local registry. If set to false, the registry would expire and attempts to locate other services will fail.

eureka.client.registerWithEureka
Specifies if this instance should register its metadata with Eureka servers to be discovered by other clients.

eureka.client.fetchRegistry
Specifies if this instance should request the Eureka registry from a Eureka server.

eureka.client.serviceUrl.defaultZone
Specifies a single or comma-separated URL of alternative Eureka server locations.

eureka.instance.hostname
The hostname where this instance is running or found out via the OS.

eureka.instance.statusPageUrlPath
Specifies the relative status page URL for this instance.

eureka.instance.healthCheckUrlPath
Specifies the relative server path to invoke for health checking.

eureka.instance.preferIpAddress
Specifies using the IP address instead of the hostname during registration.

eureka.instance.metadataMap.instanceId
Specifies the unique Id of the running instance (within the scope of this service) for registering with Eureka servers.

how to kill a service binded in particular port

Step 1

Run command-line as an Administrator. Then run the below mention command. type your port number in yourPortNumber

netstat -ano | findstr :yourPortNumber



Red coloured circled area shows the PID (process identifier)

Step 2

Then you execute this command after identify the PID.





taskkill /PID typeyourPIDhere /F


----------------------------------------------

Click the Start menu
Click Run or in the search bar type services.msc
Press Enter
Look for the service and check the Properties and identify its service name
Once found, open a command prompt. Type sc queryex [servicename].
Press Enter
Identify the PID
In the same command prompt type taskkill /pid [pid number] /f
Press Enter

NetFlix Spring Boot ZUUL Example

tp-eureka-service
==================

EurekaServiceApplication.java
=============================
package com.techprimers.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {

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

application.properties
======================
spring.application.name=eureka-service
server.port=8070


application.yml
===============
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
  server:
      waitTimeInMsWhenSyncEmpty: 0
  instance:
    hostname: localhost  

pom.xml
=======
(?xml version="1.0" encoding="UTF-8"?)
(project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")
(modelVersion)4.0.0(/modelVersion)
(groupId)com.techprimers.cloud(/groupId)
(artifactId)eureka-service(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(packaging)jar(/packaging)
(name)eureka-service(/name)
(description)Demo project for Spring Boot(/description)
(parent)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-parent(/artifactId)
(version)1.5.3.RELEASE(/version)
(relativePath/) (!-- lookup parent from repository --)
(/parent)
(properties)
(project.build.sourceEncoding)UTF-8(/project.build.sourceEncoding)
(project.reporting.outputEncoding)UTF-8(/project.reporting.outputEncoding)
(java.version)1.8(/java.version)
(/properties)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-eureka-server(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-test(/artifactId)
(scope)test(/scope)
(/dependency)
(/dependencies)
(dependencyManagement)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-dependencies(/artifactId)
(version)Dalston.RELEASE(/version)
(type)pom(/type)
(scope)import(/scope)
(/dependency)
(/dependencies)
(/dependencyManagement)
(build)
(plugins)
(plugin)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-maven-plugin(/artifactId)
(/plugin)
(/plugins)
(/build)
(/project)

Test:
====
http://localhost:8070/

---------------------------------------------------------------------------------------------------------------------

tp-hello-server
===============

HelloResource.java
==================
package com.techprimers.cloud;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rest/hello/server")
public class HelloResource {

    @GetMapping
    public String hello() {
        return "Hello World!";
    }
    @GetMapping(path="/1")
    public String hello1() {
        return "Hello World!1";
    }
    @GetMapping(path="/1/2")
    public String hello2() {
        return "Hello World!2";
    }
    @GetMapping(path="/1/2/3")
    public String hello3() {
        return "Hello World!3";
    }
}

HelloServerApplication.java
===========================
package com.techprimers.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class HelloServerApplication {

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



application.yml
===============
spring:
  application:
    name: hello-server

server:
  port: 8071

eureka:
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://localhost:8070/eureka/
  instance:
    hostname: localhost

pom.xml
=======
(?xml version="1.0" encoding="UTF-8"?)
(project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")
(modelVersion)4.0.0(/modelVersion)
(groupId)com.techprimers.cloud(/groupId)
(artifactId)hello-server(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(packaging)jar(/packaging)
(name)hello-server(/name)
(description)Demo project for Spring Boot(/description)
(parent)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-parent(/artifactId)
(version)1.5.3.RELEASE(/version)
(relativePath/) (!-- lookup parent from repository --)
(/parent)
(properties)
(project.build.sourceEncoding)UTF-8(/project.build.sourceEncoding)
(project.reporting.outputEncoding)UTF-8(/project.reporting.outputEncoding)
(java.version)1.8(/java.version)
(/properties)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-eureka(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-test(/artifactId)
(scope)test(/scope)
(/dependency)
(/dependencies)
(dependencyManagement)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-dependencies(/artifactId)
(version)Dalston.RELEASE(/version)
(type)pom(/type)
(scope)import(/scope)
(/dependency)
(/dependencies)
(/dependencyManagement)
(build)
(plugins)
(plugin)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-maven-plugin(/artifactId)
(/plugin)
(/plugins)
(/build)
(/project)

Test:
=====
http://localhost:8071/rest/hello/server

Hello World!!

-------------------------------------------------------------------------------------------------------------------------------------

tp-hello-client
===============
HelloClientApplication.java
===========================
package com.techprimers.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class HelloClientApplication {

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


@Configuration
class Config {

@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}

}

HelloResource.java
==================
package com.techprimers.cloud;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/rest/hello/client")
public class HelloResource {


    @Autowired
    private RestTemplate restTemplate;


    @HystrixCommand(fallbackMethod = "fallback", groupKey = "Hello",
            commandKey = "hello",
            threadPoolKey = "helloThread"
            )
    @GetMapping
    public String hello() {
        String url = "http://hello-server/rest/hello/server";
        return restTemplate.getForObject(url, String.class)+ " including client";
    }

    public String fallback(Throwable hystrixCommand) {
        return "Fall Back Hello world";
    }

}


application.yml
===============
spring:
  application:
    name: hello-client

server:
  port: 8072

eureka:
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://localhost:8070/eureka/
  instance:
    hostname: localhost

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 60000


pom.xml:
========
(?xml version="1.0" encoding="UTF-8"?)
(project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")
(modelVersion)4.0.0(/modelVersion)
(groupId)com.techprimers.cloud(/groupId)
(artifactId)hello-client(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(packaging)jar(/packaging)
(name)hello-client(/name)
(description)Demo project for Spring Boot(/description)
(parent)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-parent(/artifactId)
(version)1.5.3.RELEASE(/version)
(relativePath/) (!-- lookup parent from repository --)
(/parent)
(properties)
(project.build.sourceEncoding)UTF-8(/project.build.sourceEncoding)
(project.reporting.outputEncoding)UTF-8(/project.reporting.outputEncoding)
(java.version)1.8(/java.version)
(/properties)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-eureka(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-hystrix(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-test(/artifactId)
(scope)test(/scope)
(/dependency)
(/dependencies)
(dependencyManagement)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-dependencies(/artifactId)
(version)Dalston.RELEASE(/version)
(type)pom(/type)
(scope)import(/scope)
(/dependency)
(/dependencies)
(/dependencyManagement)
(build)
(plugins)
(plugin)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-maven-plugin(/artifactId)
(/plugin)
(/plugins)
(/build)
(/project)

Test:
=======
http://localhost:8072/rest/hello/client

Hello World! including client

---------------------------------------------------------------------------------------------------------------------------------------------------------

tp-zuul-service
===============

ZuulServiceApplication.java
======================
package com.techprimers.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableEurekaClient
@EnableZuulProxy
@SpringBootApplication
public class ZuulServiceApplication {

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

application.yml
===============
zuul:
  #Service will be mapped under the /api URI
  prefix: /api
  routes:
    hello-server-url:
      path: /server/**
      url: http://localhost:8071
    hello-server-eurekaId:
      path: /server1/**
      url: HELLO-SERVER
    hello-client:
      path: /client/**
      serviceId: HELLO-CLIENT

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8070/eureka/
  instance:
    hostname: localhost

server:
  port: 8079

spring:
  application:
    name: zuul-service

# Increase the Hystrix timeout to 60s (for all)
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 60000


pom.xml
=======
(?xml version="1.0" encoding="UTF-8"?)
(project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")
(modelVersion)4.0.0(/modelVersion)
(groupId)com.techprimers.cloud(/groupId)
(artifactId)zuul-service(/artifactId)
(version)0.0.1-SNAPSHOT(/version)
(packaging)jar(/packaging)
(name)zuul-service(/name)
(description)Demo project for Spring Boot(/description)
(parent)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-parent(/artifactId)
(version)1.5.3.RELEASE(/version)
(relativePath/) (!-- lookup parent from repository --)
(/parent)
(properties)
(project.build.sourceEncoding)UTF-8(/project.build.sourceEncoding)
(project.reporting.outputEncoding)UTF-8(/project.reporting.outputEncoding)
(java.version)1.8(/java.version)
(/properties)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-eureka(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-starter-zuul(/artifactId)
(/dependency)
(dependency)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-starter-test(/artifactId)
(scope)test(/scope)
(/dependency)
(/dependencies)
(dependencyManagement)
(dependencies)
(dependency)
(groupId)org.springframework.cloud(/groupId)
(artifactId)spring-cloud-dependencies(/artifactId)
(version)Dalston.RELEASE(/version)
(type)pom(/type)
(scope)import(/scope)
(/dependency)
(/dependencies)
(/dependencyManagement)
(build)
(plugins)
(plugin)
(groupId)org.springframework.boot(/groupId)
(artifactId)spring-boot-maven-plugin(/artifactId)
(/plugin)
(/plugins)
(/build)
(/project)

Test:
=====
http://localhost:8079/api/server1//rest/hello/server/1/2/3
Hello World!3

http://localhost:8079/api/server1//rest/hello/server/1/2
Hello World!2

http://localhost:8079/api/server1//rest/hello/server/1
Hello World!1

http://localhost:8079/api/server1//rest/hello/server
Hello World!

http://localhost:8079/api/client/rest/hello/client
Hello World! including client












உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...