/springboot-tuto-books-api

Springboot learning tutorial during my UDEV integration to CGI

Primary LanguageJava

spingboot-tuto-books-api

Sping Boot 2 example BOOK API projet (list books, add books, find by author or title, ...) with docker, h2 db and redis cache

  • Use lombok
  • Build and run with open jdk 8, see <java.version> maven property
  • REST controllers, see : package com.example.demo.controller
  • BookController use service, spring data with H2 mem DB (see application.properties file)
  • To changhe api port see application.properties

Build app

  • mvn clean install -U (or use maven wrapper : ./mvnw clean install or build and run with ./mvnw spring-boot:run)
  • See pom for unpack maven dependencies
  • Build Image : near Dockerfile launch docker build --no-cache -t bookapp_image:1.0.0 .

Run with docker

  • For Windows hyper-v (Win 10 min)
  • docker run -d --name appbook_micro1 -p 8080:8080 bookapp_image:1.0.0 (Detached (-d), without to see terminal log)

Other docker commands

  • docker container ls --all list containers (or docker ps)
  • docker images list images
  • docker container stop appbook_micro1 stop container
  • docker rm appbook_micro1 remove container
  • docker rmi <id-image> remove image
  • docker network rm <NETWORK> remove one or more networks

DB H2

  • In the same container than the app
  • See http://localhost:8080/api/h2-console/ (with JDBC URL : jdbc:h2:mem:testdb), to prevent H2 Console throwing a error webAllowOthers, must set spring.h2.console.settings.web-allow-others to true
  • See src/main/resources/db/runtime.sql for add data at start-up

REDIS cache

  • Only with !dev spring profile (dev mode use spring NoOpCacheManager)
  • With docker container
  • With Jedis java client. Other option si Lettuce. See here

See here to connect different docker containers. If we don't use Docker Compose :-(

docker network list
docker network create myNetwork
docker network list
docker pull redis
docker run --name my-redis-container -d -p 6379:6379 --network myNetwork redis:latest
docker run -ti --rm --name appbook_micro1 -p 8080:8080 --network myNetwork bookapp_image:1.0.0

docker network inspect myNetwork to see containers connected to our network. See here for more info.

Better to use docker compose :-). See Docker compose section !

Test

Use for instance Postman to test the REST services ... must add some books first.

POST http://localhost:8080/api/books

with payload :

{
	"title": "LOTR 1",
	"author": "toto"
}

GET http://localhost:8080/api/books/

GET http://localhost:8080/api/books/1

GET http://localhost:8080/api/books/author/toto

Docker compose

  • mvn clean install (with 'myredis' host)
  • docker-compose build (don't forget to re-build image with this after update code !)
  • docker-compose up: start
  • docker-compose down: stop

Doc