Unable to add my micro service as Eureka Client - spring

I have set a sample Micro Service using 3 spring boot applications. Post that I am trying to connect all of them to Eureka Server.
There are 3 spring Boot Applications Task-Display,Task-Repo and Task-Status-Repo.
Task Display communicates with the other two and retrieve data.
Now Problem is except Task-Display all others are linked to eureka server. Getting the following error when Task Display is deployed
2019-08-31 18:43:00.055 INFO 15528 --- [tbeatExecutor-0]
com.netflix.discovery.DiscoveryClient : DiscoveryClient_TASK-DISPLAY-
ME;/192.168.1.9:task-display-me;:8180 - Re-registering apps/TASK-DISPLAY-
ME;
2019-08-31 18:43:00.055 INFO 15528 --- [tbeatExecutor-0]
com.netflix.discovery.DiscoveryClient : DiscoveryClient_TASK-DISPLAY-
ME;/192.168.1.9:task-display-me;:8180: registering service...
2019-08-31 18:43:00.057 WARN 15528 --- [tbeatExecutor-0]
c.n.d.s.t.d.RetryableEurekaHttpClient : Request execution failure with
status code 400; retrying on another server if available
2019-08-31 18:43:00.059 WARN 15528 --- [tbeatExecutor-0]
c.n.d.s.t.d.RetryableEurekaHttpClient : Request execution failure with
status code 400; retrying on another server if available
2019-08-31 18:43:00.060 WARN 15528 --- [tbeatExecutor-0]
com.netflix.discovery.DiscoveryClient : DiscoveryClient_TASK-DISPLAY-
ME;/192.168.1.9:task-display-me;:8180 - registration failed Cannot execute
request on any known server
com.netflix.discovery.shared.transport.TransportException: Cannot execute
request on any known server
This is my Application.java of the server which is not getting linked to Eureka
#SpringBootApplication
#EnableEurekaClient
public class TaskDisplayApplication {
public static void main(String[] args) {
SpringApplication.run(TaskDisplayApplication.class, args);
}
#LoadBalanced
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}

Related

How to implement Retry logic in RabbitMQ?

In my project I'm setting SimpleRetryPolicy to add custom exception and RetryOperationsInterceptor which is consuming this policy.
#Bean
public SimpleRetryPolicy rejectionRetryPolicy() {
Map<Class<? extends Throwable>, Boolean> exceptionsMap = new HashMap<Class<? extends Throwable>, Boolean>();
exceptionsMap.put(DoNotRetryException.class, false);//not retriable
exceptionsMap.put(RetryException.class, true); //retriable
return new SimpleRetryPolicy(3, exceptionsMap, true);
}
#Bean
RetryOperationsInterceptor interceptor() {
return RetryInterceptorBuilder.stateless()
.retryPolicy(rejectionRetryPolicy())
.backOffOptions(2000L, 2, 3000L)
.recoverer(
new RepublishMessageRecoverer(rabbitTemplate(), "dlExchange", "dlRoutingKey"))
.build();
}
But with these configurations retry is not working for both RetryException and DoNotRetryException, where I want RetryException to be retried finite number of time and DoNotRetryException to send to DLQ
Please help with the issue, I'm attaching repo link if in case of need.
https://github.com/aviralnimbekar/RabbitMQ/tree/main/src
Your GlobalErrorHandler does its logic before the retry happens and you override there an exception with the AmqpRejectAndDontRequeueException. And looks like you do there a publish to DLX. Consider to move your GlobalErrorHandler logic to a more general ErrorHandler for the factory.setErrorHandler(); instead.
See more info in docs: https://docs.spring.io/spring-amqp/reference/html/#exception-handling
UPDATE
After removing errorHandler = "globalErrorHandler" from your #RabbitListener, I got this in logs:
2022-08-03 16:02:08.093 INFO 16896 --- [nio-8080-exec-4] c.t.r.producer.RabbitMQProducer : Message sent -> retry
2022-08-03 16:02:08.095 INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer : Retrying message...
2022-08-03 16:02:10.096 INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer : Retrying message...
2022-08-03 16:02:13.099 INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer : Retrying message...
2022-08-03 16:02:13.100 WARN 16896 --- [ntContainer#0-1] o.s.a.r.retry.RepublishMessageRecoverer : Republishing failed message to exchange 'dlExchange' with routing key dlRoutingKey
2022-08-03 16:02:17.736 INFO 16896 --- [nio-8080-exec-5] c.t.r.producer.RabbitMQProducer : Message sent -> 1231231
2022-08-03 16:02:17.738 INFO 16896 --- [ntContainer#0-1] c.t.r.consumer.RabbitMQConsumer : sending into dlq...
2022-08-03 16:02:17.739 WARN 16896 --- [ntContainer#0-1] o.s.a.r.retry.RepublishMessageRecoverer : Republishing failed message to exchange 'dlExchange' with routing key dlRoutingKey
Which definitely reflects your original requirements.

Spring boot pub/sub subcriber gets removed immediately after deployment

I have a spring boot app deployed to google cloud (via automatic github build).
Unfortunately my subscriber to pub/sub is being removed immediately after deployment :( Does anyone know reason for that?
Removing {service-activator:investobotAPIs.messageReceiver.serviceActivator} as a subscriber to the 'inputMessageChannel' channel
I've created a topic in google pub/sub and a subscription:
I've added these methods:
#RestController
#EnableAsync
public class InvestobotAPIs {
...
// [START pubsub_spring_inbound_channel_adapter]
// Create a message channel for messages arriving from the subscription `sub-one`.
#Bean
public MessageChannel inputMessageChannel() {
return new PublishSubscribeChannel();
}
// Create an inbound channel adapter to listen to the subscription `sub-one` and send
// messages to the input message channel.
#Bean
public PubSubInboundChannelAdapter inboundChannelAdapter(
#Qualifier("inputMessageChannel") MessageChannel messageChannel,
PubSubTemplate pubSubTemplate) {
PubSubInboundChannelAdapter adapter =
new PubSubInboundChannelAdapter(pubSubTemplate, "fetch-gpw-sub");
adapter.setOutputChannel(messageChannel);
adapter.setAckMode(AckMode.MANUAL);
adapter.setPayloadType(String.class);
return adapter;
}
// Define what happens to the messages arriving in the message channel.
#ServiceActivator(inputChannel = "inputMessageChannel")
public void messageReceiver(
String payload,
#Header(GcpPubSubHeaders.ORIGINAL_MESSAGE) BasicAcknowledgeablePubsubMessage message) {
logger.info("Message arrived via an inbound channel adapter from fetch-gpw! Payload: " + payload);
message.ack();
}
// [END pubsub_spring_inbound_channel_adapter]
and this is my build.graddle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web:2.5.5'
// get url and download files
implementation 'commons-io:commons-io:2.6'
implementation 'org.asynchttpclient:async-http-client:2.12.3'
// parse xls files
implementation 'org.apache.poi:poi:5.0.0'
implementation 'org.apache.poi:poi-ooxml:5.0.0'
// firebase messaging and db
implementation 'com.google.firebase:firebase-admin:8.1.0'
// subscribe pub/sub topic
implementation 'com.google.cloud:spring-cloud-gcp-starter-pubsub:2.0.4'
implementation 'com.google.cloud:spring-cloud-gcp-pubsub-stream-binder:2.0.4'
implementation 'com.google.cloud:spring-cloud-gcp-dependencies:2.0.4'
}
Unfortunately when it is deployed the logs show that just after deployment is gets removed:
2021-10-20 11:51:16.190 CEST2021-10-20 09:51:16.190 INFO 1 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'application.inputMessageChannel' has 1 subscriber(s).
Default
2021-10-20 11:51:16.190 CEST2021-10-20 09:51:16.190 INFO 1 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started bean 'investobotAPIs.messageReceiver.serviceActivator'
Default
2021-10-20 11:51:16.214 CEST2021-10-20 09:51:16.214 INFO 1 --- [ main] .g.c.s.p.i.i.PubSubInboundChannelAdapter : started bean 'inboundChannelAdapter'; defined in: 'class path resource [com/miloszdobrowolski/investobotbackend/InvestobotAPIs.class]'; from source: 'com.miloszdobrowolski.investobotbackend.InvestobotAPIs.inboundChannelAdapter(org.springframework.messaging.MessageChannel,com.google.cloud.spring.pubsub.core.PubSubTemplate)'
Default
2021-10-20 11:51:16.295 CEST2021-10-20 09:51:16.294 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
Default
2021-10-20 11:51:19.076 CEST2021-10-20 09:51:19.075 INFO 1 --- [ main] c.m.i.InvestobotBackendApplication : Started InvestobotBackendApplication in 14.475 seconds (JVM running for 19.248)
Info
2021-10-20 11:51:22.386 CESTCloud Runinvestobot-backend-autobuild {#type: type.googleapis.com/google.cloud.audit.AuditLog, resourceName: namespaces/our-shield-329019/services/investobot-backend-autobuild, response: {…}, serviceName: run.googleapis.com, status: {…}}
Debug
2021-10-20 11:51:54.075 CESTContainer Sandbox: Unsupported syscall setsockopt(0x16,0x29,0x31,0x3e96fd1f3a9c,0x4,0x0). It is very likely that you can safely ignore this message and that this is not the cause of any error you might be troubleshooting. Please, refer to https://gvisor.dev/c/linux/amd64/setsockopt for more information.
Debug
2021-10-20 11:51:54.075 CESTContainer Sandbox: Unsupported syscall setsockopt(0x16,0x29,0x12,0x3e96fd1f3a9c,0x4,0x0). It is very likely that you can safely ignore this message and that this is not the cause of any error you might be troubleshooting. Please, refer to https://gvisor.dev/c/linux/amd64/setsockopt for more information.
Default
2021-10-20 11:52:59.196 CEST2021-10-20 09:52:59.195 WARN 1 --- [ault-executor-0] i.g.n.s.i.n.u.internal.MacAddressUtil : Failed to find a usable hardware address from the network interfaces; using random bytes: d1:79:21:a2:71:29:47:49
Default
2021-10-20 11:53:01.010 CEST2021-10-20 09:53:01.010 INFO 1 --- [ionShutdownHook] .g.c.s.p.i.i.PubSubInboundChannelAdapter : stopped bean 'inboundChannelAdapter'; defined in: 'class path resource [com/miloszdobrowolski/investobotbackend/InvestobotAPIs.class]'; from source: 'com.miloszdobrowolski.investobotbackend.InvestobotAPIs.inboundChannelAdapter(org.springframework.messaging.MessageChannel,com.google.cloud.spring.pubsub.core.PubSubTemplate)'
Default
2021-10-20 11:53:01.010 CEST2021-10-20 09:53:01.010 INFO 1 --- [ionShutdownHook] o.s.i.endpoint.EventDrivenConsumer : Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
Default
2021-10-20 11:53:01.010 CEST2021-10-20 09:53:01.010 INFO 1 --- [ionShutdownHook] o.s.i.channel.PublishSubscribeChannel : Channel 'application.errorChannel' has 0 subscriber(s).
Default
2021-10-20 11:53:01.011 CEST2021-10-20 09:53:01.011 INFO 1 --- [ionShutdownHook] o.s.i.endpoint.EventDrivenConsumer : stopped bean '_org.springframework.integration.errorLogger'
Default
2021-10-20 11:53:01.011 CEST2021-10-20 09:53:01.011 INFO 1 --- [ionShutdownHook] o.s.i.endpoint.EventDrivenConsumer : Removing {service-activator:investobotAPIs.messageReceiver.serviceActivator} as a subscriber to the 'inputMessageChannel' channel
Default
2021-10-20 11:53:01.011 CEST2021-10-20 09:53:01.011 INFO 1 --- [ionShutdownHook] o.s.i.channel.PublishSubscribeChannel : Channel 'application.inputMessageChannel' has 0 subscriber(s).
Default
2021-10-20 11:53:01.011 CEST2021-10-20 09:53:01.011 INFO 1 --- [ionShutdownHook] o.s.i.endpoint.EventDrivenConsumer : stopped bean 'investobotAPIs.messageReceiver.serviceActivator'
I've tried to change dependencies in gradle from com.google.cloud to org.springframework.cloud (not sure how they differ)
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web:2.5.5'
// get url and download files
implementation 'commons-io:commons-io:2.6'
implementation 'org.asynchttpclient:async-http-client:2.12.3'
// parse xls files
implementation 'org.apache.poi:poi:5.0.0'
implementation 'org.apache.poi:poi-ooxml:5.0.0'
// firebase messaging and db
implementation 'com.google.firebase:firebase-admin:8.1.0'
// subscribe pub/sub topic
// implementation 'com.google.cloud:spring-cloud-gcp-starter-pubsub:2.0.4'
// implementation 'com.google.cloud:spring-cloud-gcp-pubsub-stream-binder:2.0.4'
// implementation 'com.google.cloud:spring-cloud-gcp-dependencies:2.0.4'
implementation 'org.springframework.cloud:spring-cloud-gcp-starter-bus-pubsub:1.2.8.RELEASE'
implementation 'org.springframework.cloud:spring-cloud-gcp-pubsub:1.2.8.RELEASE'
implementation 'org.springframework.cloud:spring-cloud-gcp-autoconfigure:1.2.8.RELEASE'
implementation 'org.springframework.integration:spring-integration-core:5.5.4'
}
But it only causes a different error during deployment:
ERROR: (gcloud.run.services.update) Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information.

spring config server not posting to rabbitmq

I've generated a spring boot config server from spring's initialzr.
I've installed rabbitmq with brew. initialzr generated with boot version 2.1.1.RELEASE and cloud version Greenwich.M3.
the simple rest services are connecting to rabbitmq queues. the config server is connection to a gitlab config repo.
But when I commit and push a change to it, the change is not reflected by the service application. The config server gets logs messages when the push is completed. Can anyone say what might be wrong? No messages ever seem to appear in rabbitmq console. I have been able to refresh the properties via actuator/bus-refresh through rabbitmq though.
config-server log messages on commit of change to config-repo's employee-service.yml file:
2018-12-07 11:53:12.185 INFO 84202 --- [nio-8888-exec-1] o.s.c.c.monitor.PropertyPathEndpoint : Refresh for: employee:service
2018-12-07 11:53:12.228 INFO 84202 --- [nio-8888-exec-1] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$b43cc593] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-12-07 11:53:12.253 INFO 84202 --- [nio-8888-exec-1] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default
2018-12-07 11:53:12.259 INFO 84202 --- [nio-8888-exec-1] o.s.boot.SpringApplication : Started application in 0.072 seconds (JVM running for 3075.606)
2018-12-07 11:53:12.345 INFO 84202 --- [nio-8888-exec-1] o.s.cloud.bus.event.RefreshListener : Received remote refresh request. Keys refreshed []
2018-12-07 11:53:12.345 INFO 84202 --- [nio-8888-exec-1] o.s.c.c.monitor.PropertyPathEndpoint : Refresh for: employee-service
2018-12-07 11:53:12.377 INFO 84202 --- [nio-8888-exec-1] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$b43cc593] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-12-07 11:53:12.398 INFO 84202 --- [nio-8888-exec-1] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default
2018-12-07 11:53:12.402 INFO 84202 --- [nio-8888-exec-1] o.s.boot.SpringApplication : Started application in 0.056 seconds (JVM running for 3075.749)
2018-12-07 11:53:12.489 INFO 84202 --- [nio-8888-exec-1] o.s.cloud.bus.event.RefreshListener : Received remote refresh request. Keys refreshed []
config-server has this application.yml:
---
server:
port: ${PORT:8888}
spring:
cloud:
bus:
enabled: true
config:
server:
git:
uri: ${CONFIG_REPO_URI:git#gitlab.<somedomain>:<somegroup>/config-repo.git}
search-paths:
- feature/initial-repo
main:
banner-mode: "off"
and ConfigServerApplication.java:
#SpringBootApplication
#EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
and these gradle dependencies:
dependencies {
implementation('org.springframework.cloud:spring-cloud-config-server')
implementation('org.springframework.cloud:spring-cloud-starter-stream-rabbit')
implementation('org.springframework.cloud:spring-cloud-config-monitor')
testImplementation('org.springframework.boot:spring-boot-starter-test')
implementation('org.springframework.cloud:spring-cloud-stream-test-support')
}
service has this applciation.yml:
---
server:
port: 8092
management:
security:
enabled: "false"
endpoints:
web:
exposure:
include:
- '*'
spring:
main:
banner-mode: "off"
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
this bootstrap.yml:
---
spring:
application:
name: employee-service
cloud:
config:
uri:
- http://localhost:8888
label: feature(_)initial-repo
these gradle dependencies:
dependencies {
implementation('org.springframework.boot:spring-boot-starter-web')
implementation('org.springframework.cloud:spring-cloud-starter-config')
implementation('org.springframework.cloud:spring-cloud-starter-bus-amqp')
implementation('org.springframework.boot:spring-boot-starter-actuator')
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
this main class:
#SpringBootApplication
public class EmployeeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeServiceApplication.class, args);
}
}
and this controller class:
#RefreshScope
#RestController
public class WelcomeController {
#Value("${app.service-name}")
private String serviceName;
#Value("${app.shared.attribute}")
private String sharedAttribute;
#GetMapping("/service")
public String getServiceName() {
return "service name [" + this.serviceName + "]";
}
#GetMapping("/shared")
public String getSharedAttribute() {
return " application.yml [" + this.sharedAttribute + "]";
}
}
Try to create and build your project with Maven instead of Gradle.
I experience the same problem. I have two identical apps with the same RabbitMQ dependencies, one is build with Maven and second with Gradle. The Maven-based app publishes things to RabbitMQ as expected. The very same app, built with Gradle doesn't establish connection to RabbitMQ and is not publishing events.
To further clarify things, I run both apps in Eclipse with Spring Tools.

TCP Client Spring Integration with Java Config

I am attempting to create a TCP client to connect to a remote tcp server and wait to receive messages. So far I have the following code:
#EnableIntegration
#IntegrationComponentScan
#Configuration
public class TcpClientConfig {
#Bean
public TcpInboundGateway tcpInbound(AbstractClientConnectionFactory connectionFactory) {
TcpInboundGateway gate = new TcpInboundGateway();
gate.setConnectionFactory(connectionFactory);
gate.setClientMode(false);
gate.setRequestChannel(fromTcp());
return gate;
}
#Bean
public MessageChannel fromTcp() {
return new DirectChannel();
}
#MessageEndpoint
public static class Echo {
#Transformer(inputChannel = "fromTcp", outputChannel = "serviceChannel")
public String convert(byte[] bytes) {
return new String(bytes);
}
}
#ServiceActivator(inputChannel = "serviceChannel")
public void messageToService(String in) {
System.out.println(in);
}
#Bean
public EndOfLineSerializer endOfLineSerializer() {
return new EndOfLineSerializer();
}
#Bean
public AbstractClientConnectionFactory clientConnectionFactory() {
TcpNetClientConnectionFactory tcpNetServerConnectionFactory = new TcpNetClientConnectionFactory("192.XXX.XXX.XX", 4321);
tcpNetServerConnectionFactory.setSingleUse(false);
tcpNetServerConnectionFactory.setSoTimeout(300000);
tcpNetServerConnectionFactory.setDeserializer(endOfLineSerializer());
tcpNetServerConnectionFactory.setSerializer(endOfLineSerializer());
tcpNetServerConnectionFactory.setMapper(new TimeoutMapper());
return tcpNetServerConnectionFactory;
}
}
It starts up and connects to the remote server. However, I am not receiving any data in my serviceActivator method messageToService. To assure that data exists, I can successfully connect to my remote tcp server using telnet
telnet 192.XXX.XXX.XX 4321
Trying 192.XXX.XXX.XX...
Connected to 192.XXX.XXX.XX.
Escape character is '^]'.
Hello World
I have confirmed nothing is hitting my EndOfLineSerializer. What is wrong with my TCP client?
Bonus: Let's assume the hostname and port are determined by querying an API. How would I tell the TcpNetClientConnectionFactory to wait to try to connect until I have the correct data for the port?
Debug output:
main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-11-22 23:00:46.182 DEBUG 35953 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Autodetecting user-defined JMX MBeans
2018-11-22 23:00:46.194 DEBUG 35953 --- [ main] .s.i.c.GlobalChannelInterceptorProcessor : No global channel interceptors.
2018-11-22 23:00:46.198 DEBUG 35953 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -2147483648
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'application.errorChannel' has 1 subscriber(s).
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started _org.springframework.integration.errorLogger
2018-11-22 23:00:46.198 DEBUG 35953 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Successfully started bean '_org.springframework.integration.errorLogger'
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {service-activator:tcpClientConfig.messageToService.serviceActivator} as a subscriber to the 'serviceChannel' channel
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.integration.channel.DirectChannel : Channel 'application.serviceChannel' has 1 subscriber(s).
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started tcpClientConfig.messageToService.serviceActivator
2018-11-22 23:00:46.198 DEBUG 35953 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Successfully started bean 'tcpClientConfig.messageToService.serviceActivator'
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {transformer:tcpClientConfig.Echo.convert.transformer} as a subscriber to the 'toTcp' channel
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.integration.channel.DirectChannel : Channel 'application.toTcp' has 1 subscriber(s).
2018-11-22 23:00:46.198 INFO 35953 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started tcpClientConfig.Echo.convert.transformer
2018-11-22 23:00:46.198 DEBUG 35953 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Successfully started bean 'tcpClientConfig.Echo.convert.transformer'
2018-11-22 23:00:46.198 DEBUG 35953 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2018-11-22 23:00:46.199 INFO 35953 --- [ main] .s.i.i.t.c.TcpNetClientConnectionFactory : started clientConnectionFactory, host=192.XXX.XXX.90, port=4321
2018-11-22 23:00:46.199 DEBUG 35953 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Successfully started bean 'clientConnectionFactory'
2018-11-22 23:00:46.199 INFO 35953 --- [ main] .s.i.i.t.c.TcpNetClientConnectionFactory : started clientConnectionFactory, host=192.XXX.XXX.90, port=4321
2018-11-22 23:00:46.199 INFO 35953 --- [ main] o.s.i.ip.tcp.TcpInboundGateway : started tcpInbound
2018-11-22 23:00:46.199 DEBUG 35953 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Successfully started bean 'tcpInbound'
When using a client connection factory with an inbound endpoint there is no stimulus to open a connection (client factories are normally used for outbound operations and the connection is established when the first message is sent).
When used in this mode, you need setClientMode(true). This starts a task that opens (and monitors) an outbound connection.
See the documentation
Normally, inbound adapters use a type="server" connection factory, which listens for incoming connection requests. In some cases, you may want to establish the connection in reverse, such that the inbound adapter connects to an external server and then waits for inbound messages on that connection.
This topology is supported by setting client-mode="true" on the inbound adapter. In this case, the connection factory must be of type client and must have single-use set to false.
Two additional attributes support this mechanism. retry-interval specifies (in milliseconds) how often the framework attempts to reconnect after a connection failure. scheduler supplies a TaskScheduler to schedule the connection attempts and to test that the connection is still active.
(The framework provides a default scheduler).
For your Bonus question, you would need to find the host/port before creating the application context; or create the connection factory and gateway dynamically after you have the information.

Spring Reactive MongoDB not saving document

I'm trying to save a basic document but despite connecting to mongodb successfully... It doesn't seem to want to save.
Spring logs
2018-10-03 00:17:25.998 INFO 10713 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-10-03 00:17:26.049 INFO 10713 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-10-03 00:17:26.106 INFO 10713 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-10-03 00:17:26.106 INFO 10713 --- [ restartedMain] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2018-10-03 00:17:26.112 INFO 10713 --- [ restartedMain] c.l.s.ServiceLegalApplicationKt : Started ServiceLegalApplicationKt in 3.459 seconds (JVM running for 4.201)
2018-10-03 00:17:26.644 INFO 10713 --- [ntLoopGroup-2-2] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:4}] to localhost:27017
application.properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=legal
spring.data.mongodb.repositories.type=reactive
spring.mongodb.embedded.version=4.0.2
basic interface and class
interface EventRepository: ReactiveMongoRepository<Event, String>
#Document
class Event(id: String, name: String)
trying a simple save function
#Service
class SomeService(val eventRepository: EventRepository)
{
fun save() = eventRepository.save(Event(UUID.randomUUID().toString(), "hey"))
}
Mono<Event> response = repository.save(Event(UUID.randomUUID().toString(), "hey"));
Changes in save method
fun save() = eventRepository.save(Event(UUID.randomUUID().toString(), "hey")).subscribe();
You have to invoke subscribe() method on Mono reference to see the logs or details.
To make you stream terminal with subscribe() operation and to get the Mono result at the same time - split into two separate operations:
Mono<String> myEvent = eventRepository.save(Event(UUID.randomUUID().toString(), "hey"));
myEvent.subscribe();
return myEvent;
You can also call .block() on the returned Reactive mono
Mono<Event> reactiveEvent = repository.save(); reactiveEvent.block()
Also read this

Resources