I am trying to learn Spring Boot with a tutorial. I have the code and the database, but I keep getting a Hibernate ERROR whenever I try to connect the two...
This is the Error I get:
:: Spring Boot :: (v2.7.2)
2022-08-04 19:23:59.263 INFO 13108 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1746 ms
2022-08-04 19:23:59.463 INFO 13108 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-08-04 19:24:00.560 ERROR 13108 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
I have the dependency set up in my pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
The StudentService
#Service
public class StudentService {
public List<Student> getStudents() {
return List.of(
new Student(
1L,
"Mariam",
"mariam.jamal#gmail.com",
LocalDate.of(2000, Month.JANUARY, 5),
21
)
);
}
}
And the StudentController class
#RestController
#RequestMapping(path = "api/v1/student")
public class StudentController {
private final StudentService studentService;
#Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
#GetMapping
public List<Student> getStudents() {
return studentService.getStudents();
}
}
application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/student
spring.datasource.username=postgres
spring.datasouce.password=password
spring.jpa.hibernat.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true
Unfortunately I have no idea what's the problem or what I can do to improve it. I googled, but only found "the password not filled in" (which is not the case) and "the application.properties not being in the resources folder" (which they are...)
Thank you so much already for looking through it and if I can clarify anything, I am happy to do so.
Edit: sorry for posting it as pictures I replaced everything but the error code if I should change that too just tell me
If I am correct, the version of the PostgreSQL is 14.4 the text from the pg_hba.config:
# PostgreSQL Client Authentication Configuration File
# ===================================================
#
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all scram-sha-256
# IPv4 local connections:
host all all 127.0.0.1/32 scram-sha-256
# IPv6 local connections:
host all all ::1/128 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local replication all scram-sha-256
host replication all 127.0.0.1/32 scram-sha-256
host replication all ::1/128 scram-sha-256
I fixed it by now. The problem was that I wrote hibernat instead of hibernate in the application.properties...
Related
I have rest api secured with oauth2 that I need to consume. The Authorization-grant-type is password. After obtaining access token I should request secured resource with it. The main idea is I need to acquire and refresh the access token automatically when it expires. I think it should not be kept somewhere in the session or database. Because spring security 5.2.* gives this oportunity out of the box. To do this I followed this post.
When I run the app it keeps saying that I am not authorized even if I specified the properties in application.yml.
021-07-06 16:33:15.292 INFO 25636 --- [ main] d.e.o.Oauth2clientApplication : Starting Oauth2clientApplication using Java 15.0.1 on F-LAPASOV with PID 25636 (C:\Users\f.lapasov\IdeaProjects\logwso2\oauth2client\target\classes started by f.lapasov in C:\Users\f.lapasov\IdeaProjects\logwso2\oauth2client)
2021-07-06 16:33:15.294 INFO 25636 --- [ main] d.e.o.Oauth2clientApplication : No active profile set, falling back to default profiles: default
2021-07-06 16:33:15.924 INFO 25636 --- [ main] ctiveUserDetailsServiceAutoConfiguration :
Using generated security password: 8bd88c3a-37c6-45b6-9721-ceca17e8e0bf
2021-07-06 16:33:16.173 INFO 25636 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port 9797
2021-07-06 16:33:16.181 INFO 25636 --- [ main] d.e.o.Oauth2clientApplication : Started Oauth2clientApplication in 1.168 seconds (JVM running for 1.613)
2021-07-06 16:33:16.359 INFO 25636 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-07-06 16:33:16.375 ERROR 25636 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:794) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:775) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:345) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.2.jar:2.5.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.2.jar:2.5.2]
at dev.egov.oauth2client.Oauth2clientApplication.main(Oauth2clientApplication.java:17) ~[classes/:na]
Caused by: org.springframework.web.reactive.function.client.WebClientResponseException$Unauthorized: 401 Unauthorized from GET http://ip:808/app/rest/v2/services/student/get?pin=123456789
at org.springframework.web.reactive.function.client.WebClientResponseException.create(WebClientResponseException.java:198) ~[spring-webflux-5.3.8.jar:5.3.8]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ⇢ 401 from GET http://ip:808/app/rest/v2/services/student/get?pinfl=1234567898 [DefaultWebClient]
Stack trace:
at org.springframework.web.reactive.function.client.WebClientResponseException.create(WebClientResponseException.java:198) ~[spring-webflux-5.3.8.jar:5.3.8]
*******************************
Snippet of the pom.xml file is given below
**************
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
**************
Propert file looks like below:
spring:
security:
oauth2:
client:
registration:
bael:
client-id: client
client-secret: secret
authorization-grant-type: password
provider:
bael:
token-uri: http://ip:port/app/rest/v2/oauth/token
server:
port: 9797
Configuration class for webClient:
#Configuration
public class WebClientConfig {
#Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(
clientRegistrations,
new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
oauth.setDefaultClientRegistrationId("bael");
return WebClient.builder()
.filter(oauth)
.build();
}
}
My service class:
#Service
public class WebClientService {
#Autowired
private WebClient webClient;
public String callApi(ApiRequest apiRequest) {
return webClient
.get()
.uri("http://ip:port/app/rest/v2/services/student/get",uriBuilder ->
uriBuilder
.queryParam("pin", apiRequest.getPinfl()).build()
)
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId("bael"))
.retrieve()
.bodyToMono(String.class).block();
}
}
I have a Spring Boot's application, using Cassandra DB 4.0, running into the ubuntu 16.0 with java 1.8_292.
when I start the tomcat 9, the message below appear in catalina.out log:
> 2021-05-11 22:57:49.614 WARN 1184 --- [s0-admin-1] c.d.o.d.i.c.control.ControlConnection: [s0] Error connecting to Node(endPoint=127.0.0.1:9042, hostId=null,
> 2021-05-11 22:57:49.628 WARN 1184 --- [ main] ConfigServletWebServerApplicationContext: Exception encountered during context initialization - cancelling re
> 2021-05-11 22:57:49.645 INFO 1184 --- [main] ConditionEvaluationReportLoggingListener: Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
> 2021-05-11 22:57:49.692 ERROR 1184 --- [main] o.s.boot.SpringApplication : Application run failed
I checked and the CQLSH 6 is running correct :
Connected to SSP at 127.0.0.1:9042
[cqlsh 6.0.0 | Cassandra 4.0 | CQL spec 3.4.5 | Native protocol v5]
Use HELP for help.
cqlsh>
The nodetool status is ok:
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
-- Address Load Tokens Owns (effective) Host ID Rack
UN 127.0.0.1 414.45 KiB 16 100.0% f457b508-1b91-456c-85bc-1a621c5c1d78 rack1
However the spring boot could not connect to Cassandra. And it gave me this erro [s0] Error connecting to Node(endPoint=127.0.0.1:9042, hostId=null, .
The cassandra.yaml and cassandra-env.sh are configurated the default with 127.0.0.1.
Does someone have any idea about what is happenning?
Pom.xml
<!-- https://mvnrepository.com/artifact/com.datastax.cassandra/cassandra-driver-core -->
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.datastax.spark/spark-cassandra-connector -->
<dependency>
<groupId>com.datastax.spark</groupId>
<artifactId>spark-cassandra-connector_2.12</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.12</artifactId>
<version>3.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.12</artifactId>
<version>3.1.1</version>
</dependency>
It was a Cassandra issue. Increase version of datastax/driver-java to 4.11.1. This version fixed the real problem : unexpected failure (java.lang.IllegalArgumentException: Unsupported request opcode: 0 in protocol 6).
For more details :
https://issues.apache.org/jira/browse/CASSANDRA-16636?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel
https://datastax-oss.atlassian.net/browse/JAVA-2936
I am trying to enable the actuator on an existing Spring Boot 2 application, which I thought would be straightforward as I have done few times for the application I created from scratch. However, somehow tomcat (as default server) not startup with the actuator port configured in the properties, when the application starts.
Here are snippets of the config and pom
server:
port: 8085
management:
port: 9085
<spring-boot.version>2.3.5.RELEASE</spring-boot.version>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
In the log of application startup, I can see the server port has been bound to the application but didn't see the actuator one specified in the properties.
18:32:08.435 [main] INFO o.a.c.h.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8085"]
18:32:08.524 [main] INFO o.s.b.w.e.t.TomcatWebServer - Tomcat started on port(s): 8085 (http) with context path ''
I would expect to see a port binding like the log below right after the one above.
2021-01-20 17:01:35.636 INFO 20044 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9085 (http)
I have checked the port has not been used by any other application. Did I miss anything else?
From your posting info, you should add some setting to enable endpoints. I give a sample. please try. By another word, management.port is used in spring boot 1.x.
In simple way, you just enable all endpoints and expose all. for security reason, you should make management.endpoints.enabled-by-default to false. then enable endpoint you want to expose.
management:
server:
port: 9085
endpoints:
enabled-by-default: true
web:
# base-path: /mgmt # you can change /actuator to another name
exposure:
include: "*"
# endpoint:
# refresh:
# enabled: true
# loggers:
# enabled: true
# env:
# enabled: true
Using Netflix Eureka as a Service Discovery on a Java + Spring application and getting a HTTP: 503.
When the address is fixed on the code the application works fine.
I've tried:
SpringDeveloper - Spring Developer Video
Secure Reactive Microservices - Spring Cloud Gateway from Okta Developers
Spring Cloud Hands On - Hands on Spring from Packt
Since I'm using WebFlux I need to use a #LoadBalanced over the WebClient
The service discovery pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<properties>
<java.version>11</java.version>
<spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</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>
The service discovery properties:
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
The service discovery main:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
#SpringBootApplication
#EnableEurekaServer
public class ServiceDiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceDiscoveryApplication.class, args);
}
}
The Gateway pom.xml (same , and from the Service Discovery pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
</dependencies>
The Gateway application.properties:
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
spring.application.name=gateway
server.port=8080
spring.cloud.loadbalancer.ribbon.enabled=false
The configuration Class for the Gateway:
#Component
public class LoadBalancers {
#Bean
public RouteLocator routeLocator(RouteLocatorBuilder routeLocatorBuilder){
return routeLocatorBuilder.routes()
.route("customer-service", route -> route.path("/customers")
.uri("lb://customer-service"))
.route("property-service", route -> route.path("/property")
.uri("lb://property-service"))
.build();
}
#Bean
#LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder(){
return WebClient.builder();
}
}
The service class:
#Service
public class CustomerWebService {
private static final String CUSTOMERS_WITH_ID = "/customers/{id}";
private static final String CUSTOMER_ROOT_ENDPOINT = "/customers";
private String baseUrl = "lb://customer-service/customers";
#LoadBalanced
private final WebClient.Builder webClient;
public CustomerWebService(WebClient.Builder webClient) {
this.webClient = webClient;
}
public Mono<Customer> findById(String id){
return webClient.build()
.get()
.uri(baseUrl, id)
.retrieve()
.bodyToMono(Customer.class);
}
}
When I try to execute a GET from the provider service I get the following:
2019-12-25 20:23:13.737 INFO 9552 --- [main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2019-12-25 20:23:13.738 INFO 9552 --- [main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8080
2019-12-25 20:23:14.082 INFO 9552 --- [main] b.c.i.webportal.WebportalApplication : Started WebportalApplication in 4.582 seconds (JVM running for 5.051)
2019-12-25 20:23:35.015 WARN 9552 --- [ctor-http-nio-3] o.s.c.l.core.RoundRobinLoadBalancer : No servers available for service: customer-service
2019-12-25 20:23:35.016 WARN 9552 --- [ctor-http-nio-3] eactorLoadBalancerExchangeFilterFunction : Load balancer does not contain an instance for the service customer-service
2019-12-25 20:23:35.077 ERROR 9552 --- [ctor-http-nio-3] a.w.r.e.AbstractErrorWebExceptionHandler : [e3de4777] 500 Server Error for HTTP GET "/v1/customers"
org.springframework.web.reactive.function.client.WebClientResponseException$ServiceUnavailable: 503 Service Unavailable from UNKNOWN
at org.springframework.web.reactive.function.client.WebClientResponseException.create(WebClientResponseException.java:207) ~[spring-webflux-5.2.1.RELEASE.jar:5.2.1.RELEASE]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ? 503 from GET lb://customer-service/customers [DefaultWebClient]
|_ checkpoint ? Handler br.com.imobiliariaype.webportal.controller.CustomerController#findAll() [DispatcherHandler]
|_ checkpoint ? org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
|_ checkpoint ? org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
|_ checkpoint ? HTTP GET "/v1/customers" [ExceptionHandlingWebHandler]
Stack trace:
This is the output from: http://localhost:8761/eureka/apps
<applications>
<versions__delta>1</versions__delta>
<apps__hashcode>UP_1_</apps__hashcode>
<application>
<name>CUSTOMER-SERVICE</name>
<instance>
<instanceId>WORKSTATION.mshome.net:customer-service:8060</instanceId>
<hostName>WORKSTATION.mshome.net</hostName>
<app>CUSTOMER-SERVICE</app>
<ipAddr>SOMEIP</ipAddr>
<status>UP</status>
<overriddenstatus>UNKNOWN</overriddenstatus>
<port enabled="true">8060</port>
<securePort enabled="false">443</securePort>
<countryId>1</countryId>
<dataCenterInfo class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
<name>MyOwn</name>
</dataCenterInfo>
<leaseInfo>
<renewalIntervalInSecs>30</renewalIntervalInSecs>
<durationInSecs>90</durationInSecs>
<registrationTimestamp>1577402896307</registrationTimestamp>
<lastRenewalTimestamp>1577403016236</lastRenewalTimestamp>
<evictionTimestamp>0</evictionTimestamp>
<serviceUpTimestamp>1577402895709</serviceUpTimestamp>
</leaseInfo>
<metadata>
<management.port>8060</management.port>
</metadata>
<homePageUrl>http://WORKSTATION.mshome.net:8060/</homePageUrl>
<statusPageUrl>http://WORKSTATION.mshome.net:8060/actuator/info</statusPageUrl>
<healthCheckUrl>http://WORKSTATION.mshome.net:8060/actuator/health</healthCheckUrl>
<vipAddress>customer-service</vipAddress>
<secureVipAddress>customer-service</secureVipAddress>
<isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
<lastUpdatedTimestamp>1577402896307</lastUpdatedTimestamp>
<lastDirtyTimestamp>1577402895638</lastDirtyTimestamp>
<actionType>ADDED</actionType>
</instance>
</application>
</applications>
And a picture from http://localhost:8761/
After Changes:
The log from Service Discovery:
2019-12-26 22:46:14.690 INFO 20140 --- [ Thread-10] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2019-12-26 22:46:14.718 INFO 20140 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8761 (http) with context path ''
2019-12-26 22:46:14.719 INFO 20140 --- [ main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8761
2019-12-26 22:46:14.897 INFO 20140 --- [ main] b.c.i.s.ServiceDiscoveryApplication : Started ServiceDiscoveryApplication in 4.839 seconds (JVM running for 5.348)
2019-12-26 22:46:26.374 INFO 20140 --- [nio-8761-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-12-26 22:46:26.374 INFO 20140 --- [nio-8761-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-12-26 22:46:26.379 INFO 20140 --- [nio-8761-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
2019-12-26 22:46:26.530 INFO 20140 --- [nio-8761-exec-2] c.n.e.registry.AbstractInstanceRegistry : Registered instance CUSTOMER-SERVICE/customer-service with status UP (replication=false)
2019-12-26 22:46:27.111 INFO 20140 --- [nio-8761-exec-3] c.n.e.registry.AbstractInstanceRegistry : Registered instance CUSTOMER-SERVICE/customer-service with status UP (replication=true)
The original project that I'm working on can also be found on GitHub repositories:
Consumer
Microservice Customer
Service Discovery
Service Discovery
Gateway
API Gateway
It is working for me. Not sure what went wrong in your implementation.
Here is what I tried:
Since I am not sure of your customer-service project, I created my own with following files:
CustomerServiceApplication
#SpringBootApplication
#EnableDiscoveryClient
public class CustomerServiceApplication {
public static void main(String[] args) {
SpringApplication.run(CustomerServiceApplication.class, args);
}
}
CustomerServiceController
#RestController("/customers")
public class CustomerServiceController {
#GetMapping("/{id}")
public String getId(#PathVariable("id") String id) {
return "Customer";
}
}
application.properties
server.port=8081
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
spring.application.name=customer-service
eureka.instance.appname=customer-service
Coming to Gateway application, I added the following files:
CustomerWebService
#Service
public class CustomerWebService {
private static final String CUSTOMERS_WITH_ID = "/customers/{id}";
private static final String CUSTOMER_ROOT_ENDPOINT = "/customers";
private String baseUrl = "lb://customer-service/customers";
#LoadBalanced
private final WebClient.Builder webClient;
public CustomerWebService(WebClient.Builder webClient) {
this.webClient = webClient;
}
public Mono<String> findById(String id) {
return webClient.build()
.get()
.uri(baseUrl, id)
.retrieve()
.bodyToMono(String.class);
}
}
LoadBalancers
#Component
public class LoadBalancers {
#Bean
public RouteLocator routeLocator(RouteLocatorBuilder routeLocatorBuilder) {
return routeLocatorBuilder.routes()
.route("customer-service", route -> route.path("/customers")
.uri("lb://customer-service"))
.build();
}
#Bean
#LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
}
InstanceListener - runs every 30 seconds on eureka heartbeat
#Component
public class InstanceListener implements ApplicationListener<HeartbeatEvent> {
#Autowired
private CustomerWebService customerWebService;
#Override
public void onApplicationEvent(HeartbeatEvent event) {
Mono<String> result = customerWebService.findById("id");
result.subscribe(
value -> System.out.println(value),
error -> error.printStackTrace()
);
}
}
application.properties
eureka.client.enabled=true
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
Every 30 seconds, I was able to see call happening to customer-service and Gateway displaying Customer value in console.
Try exactly what I did and see if it is working. Let me know. thanks
I've had the same problem and found that it happens to because of missing #LoadBalanced annotation in WebClient.Builder bean. I define that in the Application Class like below:
#SpringBootApplication
#EnableEurekaClient
public class MovieCatalogueServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MovieCatalogueServiceApplication.class, args);
}
#Bean
#LoadBalanced
public WebClient.Builder getWebClientBuilder() {
return WebClient.builder();
}
}
I am able to use RABBITMQ and MYSQLSERVICES which is on pivotal.While binding services I am able to get the Credentials and using that credentials in my application.properties for spring data jpa project.
But this configuration that I am using is hard-coded in application.Properties To Make this configuration dynamically I came to know that we can use vcap services provided by pivotal.
So want to use run-time credentials for rabbimq and mysql.
My Code is below for reference.
File: application.propeties
rabbitmq.host=hostname
rabbitmq.virtual-host=vhost
rabbitmq.username=username
rabbitmq.password=password
rabbit.mainqueue=queue name
rabbit.errorqueue=erro queue name
spring.datasource.url=jdbc:mysql://hostname:postno
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
server.port=8000
The below is the repository file
package com.redistomysql.consumer.repo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface tblemployee_personal_infoRepository extends JpaRepository<tblemployee_personal_info, Long> {
}
Any help would be appreciated.
The link for reference **http://www.java-allandsundry.com/2016/05/approaches-to-binding-spring-boot.html**
Set this configuration in application-cloud.yml for Mysql
---
spring:
datasource:
url: ${vcap.services.mydb.credentials.jdbcUrl}
username: ${vcap.services.mydb.credentials.username}
password: ${vcap.services.mydb.credentials.password}
The config for rabbitMq:
System.getEnv("VCAP_SERVICES")
The dependencies in pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-spring-service-connector</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>
<!-- If you intend to deploy the app on Cloud Foundry, add the following -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-cloudfoundry-connector</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-heroku-connector</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>
**The manifest.yml**
---
applications:
- name: redistomysql-consumer
path: target/redistomysql-consumer-0.0.1-SNAPSHOT.jar
memory: 1024M
env:
JAVA_OPTS: -Djava.security.egd=file:/dev/./urandom
SPRING_PROFILES_ACTIVE: cloud
services:
- es-mysql-db
- es-consumer-rabbitmq-service
buildpack: https://github.com/cloudfoundry/java-buildpack.git
env:
JBP_CONFIG_SPRING_AUTO_RECONFIGURATION: '{enabled: false}'