loadbalanced ribbon client initialization against discovery service (eureka) - spring-cloud

I have service which runs some init scripts after application startup (implemented with ApplicationListener<ApplicationReadyEvent>). In this scripts I need to call another services with RestTemplate which is #LoadBalanced. When the call to service is invoked there's no information about instances of remote service because discovery server was not contacted at that time (I guess).
java.lang.IllegalStateException: No instances available for api-service
at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:79)
So is there way how to get list of available services from discovery server at application startup, before my init script will execute?
Thanks
edit:
The problem is more related to fact, that in current environment (dev) all services are tied together in one service (api-service). So from within api-service I'm trying to call #LoadBalanced client api-service which doesn't know about self? Can I register some listener or something similar to know when api-service (self) will be available?
here are the sample applications. I'm mainly interested how to have working this method
edit2:
Now there could be the solution to create EurekaListener
public static class InitializerListener implements EurekaEventListener {
private EurekaClient eurekaClient;
private RestOperations restTemplate;
public InitializerListener(EurekaClient eurekaClient, RestOperations restTemplate) {
this.eurekaClient = eurekaClient;
this.restTemplate = restTemplate;
}
#Override
public void onEvent(EurekaEvent event) {
if (event instanceof StatusChangeEvent) {
if (((StatusChangeEvent) event).getStatus().equals(InstanceInfo.InstanceStatus.UP)) {
ResponseEntity<String> helloResponse = restTemplate.getForEntity("http://api-service/hello-controller/{name}", String.class, "my friend");
logger.debug("Response from controller is {}", helloResponse.getBody());
eurekaClient.unregisterEventListener(this);
}
}
}
}
and then register it like this:
EurekaEventListener initializerListener = new InitializerListener(discoveryClient, restTemplate);
discoveryClient.registerEventListener(initializerListener);
However this is only executed only when application is registered to discovery service first time. Next time when I stop the api-service and run it again, event is not published. Is there any other event which can I catch?

Currently, in Camden and earlier, applications are required to be registered in Eureka before they can query for other applications. Your call is likely too early in the registration lifecycle. There is an InstanceRegisteredEvent that may help. There are plans to work on this in the Dalston release train.

Related

Discovery / Registration only works when K8s pod already registered.

Thanks for Spring Boot Admin!
I am using it with Spring Cloud Kubernetes, our k8s pods only get discovered when we start the Spring Boot Admin, after the service pods have been started.
It seems looking at InstanceDiscoveryListener, the discovery of clients,
will happen based on events. Like ApplicationReadyEvent (When starting) and i.e. InstanceRegisteredEvent.
Is it correct to say, that Spring Boot Admin, will not try to discover periodically? If so how do I make sure an event is fired from the application to Spring boot admin picks it up and registers the instance?
Especially to make sure, that instanced are registered when they are started after spring boot admin, was started. (The order in which k8s pods are started is arbitrary/hard to control, something in general we don't want to do).
Thank You!
Christophew
Version:
springBootAdminVersion = '2.0.1'
springCloudVersion = 'Finchley.RELEASE'
springCloudK8s = '0.3.0.RELEASE'
Not sure if this is the best way to solve it but seems to work:
class TimedInstanceDiscoveryListener extends InstanceDiscoveryListener {
private static final Logger log = LoggerFactory.getLogger(TimedInstanceDiscoveryListener.class);
public TimedInstanceDiscoveryListener(DiscoveryClient discoveryClient, InstanceRegistry registry, InstanceRepository repository) {
super(discoveryClient, registry, repository);
log.info("Starting custom TimedInstanceDiscoveryListener");
}
#Scheduled(fixedRate = 5000)
public void periodicDiscovery() {
log.info("Discovering new pod / services");
super.discover();
}
}
#Bean
#ConfigurationProperties(prefix = "spring.boot.admin.discovery")
public InstanceDiscoveryListener instanceDiscoveryListener(ServiceInstanceConverter serviceInstanceConverter,
DiscoveryClient discoveryClient,
InstanceRegistry registry,
InstanceRepository repository) {
InstanceDiscoveryListener listener = new TimedInstanceDiscoveryListener(discoveryClient, registry, repository);
listener.setConverter(serviceInstanceConverter);
return listener;
}

Relation between rest camel and mongodb

I novice in camel.
What i have:
- rest app deployed on tomcat
- mongodb
What i want to do:
I want to send request from rest app to camel and camel send request to mongodb and then camel send response to the rest app. (request rest -> camel -> mongodb , response mongodb->camel->rest )
I can't find information about it.
how i can do this?
my Rest class
#Path("/leave")
public class Leave {
#GET
#Path("/all")
#Produces("application/json")
public String getLeaveRequestList(){
return "{\"status\":200}";
}}
my route
public class CamelRouteConfig extends RouteBuilder {
#Override
public void configure() throws Exception {
restConfiguration().host("localhost").port(8080);
rest("/leave")
.post("/all")
.consumes("application/json")
.to("stream:out");
}
}
it do nothing. why? - i have no idea
contex method
CamelRouteConfig routeConfig = new CamelRouteConfig();
CamelContext context = new DefaultCamelContext();
try {
context.addRoutes(routeConfig);
context.start();
}finally {
context.stop();
}
thx for your attention!
You are running Camel as standalone. When you call context.start(), the method does not block. It means that after starting, context.stop() is called immediately. Camel shuts down and REST service goes down with it.
See the following articles: Running Camel standalone and have it keep runninge and running Camel standalone.
Use class org.apache.camel.main.Main and use run() method:
From run javadoc:
Runs this process with the given arguments, and will wait until completed, or the JVM terminates.
Throws:
Exception

SOAP service in AEM 6.2

I'm trying to create a SOAP service in AEM 6.2 (the client cant make a REST call). Right now its up and works, the problem is when we redeploy or the AEM instance is reset... then the port of the service gets locked. Error on "create()".
final JaxWsServerFactoryBean jaxWsServerFactoryBean = new JaxWsServerFactoryBean();
jaxWsServerFactoryBean.setServiceClass(getWebServiceClass());
jaxWsServerFactoryBean.setAddress(this.webServiceAddress);
jaxWsServerFactoryBean.setServiceBean(this);
jaxWsServerFactoryBean.getInInterceptors().add(new LoggingInInterceptor());
jaxWsServerFactoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
server = jaxWsServerFactoryBean.create();
*ERROR* [OsgiInstallerImpl] org.apache.cxf.transport.http_jetty.JettyHTTPServerEngine Could not start Jetty server on port 4,517: Address already in use: bind
The first time I deploy works fine but then I have to change port for each redeploy... I'm closing the server if exists before that create, and if I call "isStarted()" it says false.
server.getDestination().shutdown();
server.stop();
server.destroy();
Really stuck for days on this, thank you for your help.
You should create a OSGI bundle and create your soap service inside the bundle.
#Activate
public void activate(BundleContext bundleContext) throws Exception {
... start your soap service
}
#Deactivate
public void deactivate() throws Exception {
... stop your soap service
}
Now you can restart your soap service by restarting the bundle. here is reference how to create a OSGI bundle. http://www.aemcq5tutorials.com/tutorials/create-osgi-bundle-in-aem/

annotation #RibbonClient not work together with RestTemplate

I am trying Ribbon configuration with RestTemplate based on bookmark service example but without luck, here is my code:
#SpringBootApplication
#RestController
#RibbonClient(name = "foo", configuration = SampleRibbonConfiguration.class)
public class BookmarkServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BookmarkServiceApplication.class, args);
}
#Autowired
RestTemplate restTemplate;
#RequestMapping("/hello")
public String hello() {
String greeting = this.restTemplate.getForObject("http://foo/hello", String.class);
return String.format("%s, %s!", greeting);
}
}
with error page as below:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Mar 22 19:59:33 GMT+08:00 2016
There was an unexpected error (type=Internal Server Error, status=500).
No instances available for foo
but if I remove annotation #RibbonClient, everything will be just ok,
#RibbonClient(name = "foo", configuration = SampleRibbonConfiguration.class)
and here is SampleRibbonConfiguration implementation:
public class SampleRibbonConfiguration {
#Autowired
IClientConfig ribbonClientConfig;
#Bean
public IPing ribbonPing(IClientConfig config) {
return new PingUrl();
}
#Bean
public IRule ribbonRule(IClientConfig config) {
return new AvailabilityFilteringRule();
}
}
Is it because RibbonClient can not work with RestTemplate together?
and another question is that does Ribbon configuration like load balancing rule could be configured via application.yml configuration file?
as from Ribbon wiki, seems we can configure Ribbon parameters like NFLoadBalancerClassName, NFLoadBalancerRuleClassName etc in property file, does Spring Cloud also supports this?
I'm going to assume you're using Eureka for Service Discovery.
Your particular error:
No instances available for foo
can happen for a couple of reasons
1.) All services are down
All of the instances of your foo service could legitimately be DOWN.
Solution: Try visiting your Eureka Dashboard and ensure all the services are actually UP.
If you're running locally, the Eureka Dashboard is at http://localhost:8761/
2.) Waiting for heartbeats
When you very first register a service via Eureka, there's a period of time where the service is UP but not available. From the documentation
A service is not available for discovery by clients until the
instance, the server and the client all have the same metadata in
their local cache (so it could take 3 heartbeats)
Solution: Wait a good 30 seconds after starting your foo service before you try calling it via your client.
In your particular case I'm going to guess #2 is likely what's happening to you. You're probably starting the service and trying to call it immediately from the client.
When it doesn't work, you stop the client, make some changes and restart. By that time though, all of the heartbeats have completed and your service is now available.
For your second question. Look at the "Customizing the Ribbon Client using properties" section in the reference documentation. (link)

ClassCastException On JBOSS OSGI 7.1

I use JBOSS OSGI 7.1 for my project.
I have 2 bundle:
usermanagement (service provider)
jerseyBundle (service consumer)
When I deploy and start usermanagement bundle,
Then deploy and start jersey bundle.
jerseyBundle getServiceReference() successful.
Then.
I try to redeploy and restart usermanagement. Then refresh all bundles.
JerseyBundle getServiceReference() with Exception: "ClassCastException"
This is code I use to get service:
public <T> T getService(Class<T> type,List<ServiceReference> _sref) {
try {
ServiceReference sref = bundleContext.getServiceReference(type.getName());
if(sref != null)
{
_sref.add(sref);
}
return type.cast(bundleContext.getService(sref));
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
I use blueprint to register services.
I tried to ungetservice but it don't solved this problem.
public void unGetService(List<ServiceReference> _sref) {
try{
while(_sref != null && _sref.size() >0 )
{
System.err.println("==============" + bundleContext.ungetService(_sref.remove(0)));
}
}catch(Exception ex){
ex.printStackTrace();
}
}
Are there any ways to redeploy service provider bundle, don't need redeploy service consumer bundle?
The reason for the observed behaviour may be that OSGi caches the service object by bundle. So if you do bundleContext.getService(sref) then OSGI will store this object internally and always return the same until you do ungetService.
So when you update the service bundle which also contains the interface and refresh the client you will have a new class for the interface. If you now do a cast of an old service object to the new interface the ClassCastException will occur.
One way to cope with this is to only use the service object for a short period of time and then unget it. Like this:
ServiceReference sref = bundleContext.getServiceReference(type.getName());
myO = type.cast(bundleContext.getService(sref));
doStuff(myO);
bundleContext.ungetService(sref)
Of course this is only practicable for infrequent calls as you have some overhead.
The other way is to use a ServiceTracker and react on service additions and removals. So for example you could inject a service into your class which does "doStuff" and remove / replace the service when there are changes. This is quite hard to do on your own though.
In fact this is the reason why there are frameworks like declarative services (DS) or blueprint. These make sure to reinject service and restart your components when services come and go.
As you are already using blueprint on the provider side you might try to use it on the client side too. The blueprint client should not have the problems you observed.
Btw. blueprint and DS handle service dynamics very differently. Blueprint injects a proxy once and then just replaces the service object inside the proxy while DS will really restart your user component.