1

I have 2 spring microservice Applications and want them to access the same DB. But both Applications create a different databases when i run them. The Application.yml files:

Service 1:

server.port: 8002

logging:
  level:
    org:
      springframework:
        jdbc:
          core:
            DEBUG

spring:
  application:
    name: movie
  datasource:
    url: jdbc:h2:mem:movie_service
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true

eureka:
  client:
    serviceUrl:
      defaultZone: ${EUREKA_URI:http://localhost:8001/eureka}
    registryFetchIntervalSeconds: 1
  instance:
    leaseRenewalIntervalInSeconds: 1
    #preferIpAddress: true
eureka.instance.prefer-ip-address: false

Service 2:

server.port: 8003

spring:
  application.name: client
  datasource:
    url: jdbc:h2:mem:movie_service
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true

logging:
  level:
    org:
      springframework:
        jdbc:
          core:
            DEBUG

eureka:
  client:
    serviceUrl:
      defaultZone: ${EUREKA_URI:http://localhost:8001/eureka}
    registryFetchIntervalSeconds: 1
  instance:
    leaseRenewalIntervalInSeconds: 1
    #preferIpAddress: true
eureka.instance.prefer-ip-address: false

I thought by providing the same URL, one service will create the DB and the other one will just use it.

Asperator
  • 23
  • 4
  • 1
    It's not recommended to share database between microservices. See this post : https://stackoverflow.com/questions/43612866/microservices-with-shared-database-using-multiple-orms – Katy Jul 11 '20 at 18:43

1 Answers1

3

H2 is an in memory database, use a database that allows multiple users.

UPDATE:

actually, I was not precise. H2 has a server mode, but you are running the database embedded in your application.

You need the database as a service and then you can connect from your microservice applications to that running database.

As a side note, it is a common antipattern to have different microservices accessing the same database.

The database - if it is shared at all - should only be shared by instances of one microservice component.

thst
  • 4,592
  • 1
  • 26
  • 40
  • In my case its ok to have one user. In every Service i create a table with a foreignKey connecting these tables. I just want them to create the tables in the same DB. – Asperator Jul 11 '20 at 18:35
  • No, from an architectural point, you are breaking the independence of the microservices. It may be ok for your application at this level (play project) but it leads to a macro-service architecture and deployment monoliths to have. You will find yourself selecting tables you don't own and thus building high coupling between your services over the database schema. As a consequence, you will not be able to update services and data models independently. – thst Jul 11 '20 at 18:40
  • Thank you very much. This makes totally sense. I changed my architecture accordingly. – Asperator Jul 11 '20 at 21:19