diff --git a/pom.xml b/pom.xml index dd829833bd..9b41e7446c 100644 --- a/pom.xml +++ b/pom.xml @@ -560,8 +560,7 @@ spring-boot-rest spring-caching - spring-caching-2/redis - spring-caching-2/ttl + spring-caching-2 spring-cloud-modules diff --git a/spring-caching-2/redis/pom.xml b/spring-caching-2/pom.xml similarity index 83% rename from spring-caching-2/redis/pom.xml rename to spring-caching-2/pom.xml index a772a7b031..5f982fbad2 100644 --- a/spring-caching-2/redis/pom.xml +++ b/spring-caching-2/pom.xml @@ -6,13 +6,13 @@ spring-caching-2 0.1-SNAPSHOT spring-caching-2 - war + jar com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-2/pom.xml + ../parent-boot-2/pom.xml @@ -63,4 +63,16 @@ 0.7.3 + + + + resources + ${project.build.outputDirectory} + + application.properties + + + + + \ No newline at end of file diff --git a/spring-caching-2/redis/README.md b/spring-caching-2/redis/README.md deleted file mode 100644 index 1375b5e8e4..0000000000 --- a/spring-caching-2/redis/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles: - -- [Spring Boot Cache with Redis](https://www.baeldung.com/spring-boot-redis-cache) diff --git a/spring-caching-2/redis/src/main/resources/data.sql b/spring-caching-2/redis/src/main/resources/data.sql deleted file mode 100644 index 74e359b877..0000000000 --- a/spring-caching-2/redis/src/main/resources/data.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO ITEM VALUES('abc','ITEM1'); \ No newline at end of file diff --git a/spring-caching-2/redis/src/test/resources/logback-test.xml b/spring-caching-2/redis/src/test/resources/logback-test.xml deleted file mode 100644 index 215403c6a5..0000000000 --- a/spring-caching-2/redis/src/test/resources/logback-test.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/CacheConfig.java b/spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java similarity index 61% rename from spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/CacheConfig.java rename to spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java index 89bdc2779d..673ce8e4ff 100644 --- a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/CacheConfig.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java @@ -16,18 +16,18 @@ public class CacheConfig { @Bean public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() { return (builder) -> builder - .withCacheConfiguration("itemCache", - RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10))) - .withCacheConfiguration("customerCache", - RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5))); + .withCacheConfiguration("itemCache", + RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10))) + .withCacheConfiguration("customerCache", + RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5))); } @Bean public RedisCacheConfiguration cacheConfiguration() { return RedisCacheConfiguration.defaultCacheConfig() - .entryTtl(Duration.ofMinutes(60)) - .disableCachingNullValues() - .serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); + .entryTtl(Duration.ofMinutes(60)) + .disableCachingNullValues() + .serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); } -} +} \ No newline at end of file diff --git a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/Item.java b/spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java similarity index 99% rename from spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/Item.java rename to spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java index d6115a4833..20b3e7d017 100644 --- a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/Item.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java @@ -18,4 +18,4 @@ public class Item implements Serializable { String id; String description; -} +} \ No newline at end of file diff --git a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemController.java b/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java similarity index 99% rename from spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemController.java rename to spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java index 63122c5938..7cd2e3a8c3 100644 --- a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemController.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java @@ -16,4 +16,4 @@ public class ItemController { return itemService.getItemForId(id); } -} +} \ No newline at end of file diff --git a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemRepository.java b/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java similarity index 98% rename from spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemRepository.java rename to spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java index d6222de621..609e555c1c 100644 --- a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemRepository.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java @@ -3,4 +3,4 @@ package com.baeldung.caching.redis; import org.springframework.data.repository.CrudRepository; public interface ItemRepository extends CrudRepository { -} +} \ No newline at end of file diff --git a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemService.java b/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java similarity index 88% rename from spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemService.java rename to spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java index 6a59c7d74e..fdb6f975a0 100644 --- a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/ItemService.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java @@ -13,7 +13,7 @@ public class ItemService { @Cacheable(value = "itemCache") public Item getItemForId(String id) { return itemRepository.findById(id) - .orElseThrow(RuntimeException::new); + .orElseThrow(RuntimeException::new); } -} +} \ No newline at end of file diff --git a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java b/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java similarity index 99% rename from spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java rename to spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java index 3b337def01..2be0cc6ff2 100644 --- a/spring-caching-2/redis/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java @@ -11,4 +11,4 @@ public class RedisCacheApplication { public static void main(String[] args) { SpringApplication.run(RedisCacheApplication.class, args); } -} +} \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/Application.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java similarity index 75% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/Application.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java index b8f337bcf7..f6f1a13727 100755 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/Application.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java @@ -6,8 +6,8 @@ import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling -public class Application { +public class CachingTTLApplication { public static void main(String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(CachingTTLApplication.class, args); } } \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java similarity index 79% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java index f1a90eb950..f489e979ff 100755 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java @@ -5,7 +5,6 @@ import com.baeldung.caching.ttl.model.Hotel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @@ -27,10 +26,4 @@ public class HotelController { public List getAllHotels() { return hotelService.getAllHotels(); } - - @GetMapping(value = "/{id}") - @ResponseStatus(HttpStatus.OK) - public Hotel getHotelById(@PathVariable Long id) { - return hotelService.getHotelById(id); - } } \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/City.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java similarity index 86% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/City.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java index 88902d7e05..5c9ea2098a 100644 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/City.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java @@ -17,7 +17,7 @@ public class City implements Serializable { private String name; - private double cityCentreLatitude; + private double cityCentreLattitude; private double cityCentreLongitude; public City() {} @@ -25,7 +25,7 @@ public class City implements Serializable { public City(Long id, String name, double cityCentreLatitude, double cityCentreLongitude) { this.id = id; this.name = name; - this.cityCentreLatitude = cityCentreLatitude; + this.cityCentreLattitude = cityCentreLatitude; this.cityCentreLongitude = cityCentreLongitude; } @@ -42,7 +42,7 @@ public class City implements Serializable { } public double getCityCentreLatitude() { - return cityCentreLatitude; + return cityCentreLattitude; } public double getCityCentreLongitude() { @@ -56,7 +56,7 @@ public class City implements Serializable { City city = (City) o; - if (Double.compare(city.cityCentreLatitude, cityCentreLatitude) != 0) return false; + if (Double.compare(city.cityCentreLattitude, cityCentreLattitude) != 0) return false; if (Double.compare(city.cityCentreLongitude, cityCentreLongitude) != 0) return false; if (!Objects.equals(id, city.id)) return false; return Objects.equals(name, city.name); diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/Hotel.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java similarity index 92% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/Hotel.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java index ffb4f298c8..4244d339e4 100755 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/model/Hotel.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java @@ -22,7 +22,7 @@ public class Hotel implements Serializable { private City city; private String address; - private double latitude; + private double lattitude; private double longitude; private boolean deleted = false; @@ -34,7 +34,7 @@ public class Hotel implements Serializable { Double rating, City city, String address, - double latitude, + double lattitude, double longitude, boolean deleted) { this.id = id; @@ -42,7 +42,7 @@ public class Hotel implements Serializable { this.rating = rating; this.city = city; this.address = address; - this.latitude = latitude; + this.lattitude = lattitude; this.longitude = longitude; this.deleted = deleted; } @@ -88,11 +88,11 @@ public class Hotel implements Serializable { } public double getLatitude() { - return latitude; + return lattitude; } public void setLatitude(double latitude) { - this.latitude = latitude; + this.lattitude = latitude; } public double getLongitude() { @@ -118,7 +118,7 @@ public class Hotel implements Serializable { Hotel hotel = (Hotel) o; - if (Double.compare(hotel.latitude, latitude) != 0) return false; + if (Double.compare(hotel.lattitude, lattitude) != 0) return false; if (Double.compare(hotel.longitude, longitude) != 0) return false; if (deleted != hotel.deleted) return false; if (!Objects.equals(id, hotel.id)) return false; diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java similarity index 67% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java index 6ce5ca9e76..1dee17d86f 100755 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java +++ b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java @@ -16,13 +16,4 @@ public interface HotelRepository extends JpaRepository { } return findAll(); } - - default Optional getHotelById(Long hotelId) { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - return findById(hotelId); - } } \ No newline at end of file diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java new file mode 100755 index 0000000000..abc2b18521 --- /dev/null +++ b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java @@ -0,0 +1,35 @@ +package com.baeldung.caching.ttl.service; + +import com.baeldung.caching.ttl.repository.HotelRepository; +import com.baeldung.caching.ttl.model.Hotel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class HotelService { + + private final HotelRepository hotelRepository; + Logger logger = LoggerFactory.getLogger(HotelService.class); + + HotelService(HotelRepository hotelRepository) { + this.hotelRepository = hotelRepository; + } + + @Cacheable("hotels") + public List getAllHotels() { + return hotelRepository.getAllHotels(); + } + + @CacheEvict(value = "hotels", allEntries = true) + @Scheduled(fixedRateString = "43200") + public void emptyHotelsCache() { + logger.info("emptying Hotels cache"); + } + +} \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java b/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java similarity index 100% rename from spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java rename to spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java diff --git a/spring-caching-2/redis/src/main/resources/application.properties b/spring-caching-2/src/main/resources/application.properties similarity index 78% rename from spring-caching-2/redis/src/main/resources/application.properties rename to spring-caching-2/src/main/resources/application.properties index 080185b620..38f3537d01 100644 --- a/spring-caching-2/redis/src/main/resources/application.properties +++ b/spring-caching-2/src/main/resources/application.properties @@ -2,11 +2,12 @@ spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= - # Enabling H2 Console spring.h2.console.enabled=true spring.h2.console.path=/h2 - +spring.jpa.hibernate.ddl-auto=update +#setting cache TTL +caching.spring.hotelListTTL=43200 # Connection details #spring.redis.host=localhost #spring.redis.port=6379 diff --git a/spring-caching-2/src/main/resources/data.sql b/spring-caching-2/src/main/resources/data.sql new file mode 100644 index 0000000000..027a8b5f01 --- /dev/null +++ b/spring-caching-2/src/main/resources/data.sql @@ -0,0 +1,67 @@ +DROP TABLE IF EXISTS ITEM; +create table ITEM +( + ID CHARACTER VARYING not null, + DESCRIPTION CHARACTER VARYING, + constraint ITEM_PK + primary key (ID) +); +DROP TABLE IF EXISTS HOTEL; +DROP TABLE IF EXISTS CITY; +create table CITY +( + id bigint, + name varchar, + city_centre_lattitude double, + city_centre_longitude double, + constraint city_pk + primary key (id) +); +create table hotel +( + id bigint auto_increment, + name varchar, + deleted boolean, + rating double, + city_id bigint, + address varchar, + lattitude varchar, + longitude varchar, + constraint hotel_pk + primary key (id), + constraint "hotel_CITY_null_fk" + foreign key (city_id) references CITY (id) +); + + +INSERT INTO ITEM VALUES('abc','ITEM1'); + + +INSERT INTO city(id, name, city_centre_lattitude, city_centre_longitude) +VALUES (1, 'Amsterdam', 52.368780, 4.903303); +INSERT INTO city(id, name, city_centre_lattitude, city_centre_longitude) +VALUES (2, 'Manchester', 53.481062, -2.237706); + + +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Monaghan Hotel', false, 9.2, 1, 'Weesperbuurt en Plantage', 52.364799, 4.908971); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('The Thornton Council Hotel', false, 6.3, 1, 'Waterlooplein', 52.3681563, 4.9010029); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('McZoe Trescothiks Hotel', false, 9.8, 1, 'Oude Stad, Harlem', 52.379577, 4.633547); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Stay Schmtay Hotel', false, 8.7, 1, 'Jan van Galenstraat', 52.3756755, 4.8668628); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Fitting Image Hotel', false, NULL, 1, 'Staatsliedenbuurt', 52.380936, 4.8708297); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Raymond of Amsterdam Hotel', false, NULL, 1, '22 High Avenue', 52.3773989, 4.8846443); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('201 Deansgate Hotel', false, 7.3, 2, '201 Deansgate', 53.4788305, -2.2484721); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Fountain Street Hotel', true, 3.0, 2, '35 Fountain Street', 53.4811298, -2.2402227); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Sunlight House', false, 4.3, 2, 'Little Quay St', 53.4785129, -2.2505943); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('St Georges House', false, 9.6, 2, '56 Peter St', 53.477822, -2.2462002); +INSERT INTO hotel(name, deleted, rating, city_id, address, lattitude, longitude) +VALUES ('Marriot Bonvoy', false, 9.6, 1, 'Hans Zimmerstraat', 53.477872, -2.2462003); \ No newline at end of file diff --git a/spring-caching-2/redis/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java similarity index 98% rename from spring-caching-2/redis/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java rename to spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index 71a9729efd..291e729fb9 100644 --- a/spring-caching-2/redis/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -45,7 +45,7 @@ class ItemServiceCachingIntegrationTest { void givenRedisCaching_whenFindItemById_thenItemReturnedFromCache() { Item anItem = new Item(AN_ID, A_DESCRIPTION); given(mockItemRepository.findById(AN_ID)) - .willReturn(Optional.of(anItem)); + .willReturn(Optional.of(anItem)); Item itemCacheMiss = itemService.getItemForId(AN_ID); Item itemCacheHit = itemService.getItemForId(AN_ID); @@ -81,4 +81,4 @@ class ItemServiceCachingIntegrationTest { } } -} +} \ No newline at end of file diff --git a/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java b/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java new file mode 100644 index 0000000000..f36c794361 --- /dev/null +++ b/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.caching.ttl; + +import com.baeldung.caching.ttl.repository.HotelRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@AutoConfigureMockMvc +@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:data.sql") +@SlowTest +class HotelControllerIntegrationTest { + @Autowired private MockMvc mockMvc; + @Autowired private HotelRepository repository; + + @Test + @DisplayName("When all hotels requested then request is successful") + void whenAllHotelsRequested_thenRequestIsSuccessful() throws Exception { + mockMvc + .perform(get("/hotel")) + .andExpect(status().isOk()); + } + + @Test + @DisplayName("When all hotels are requested then they correct number of hotels is returned") + void whenAllHotelsRequested_thenReturnAllHotels() throws Exception { + mockMvc + .perform(get("/hotel")) + .andExpect(jsonPath("$", hasSize((int) repository.findAll().stream().count()))); + } +} \ No newline at end of file diff --git a/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java b/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java new file mode 100644 index 0000000000..60e8abcd14 --- /dev/null +++ b/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java @@ -0,0 +1,4 @@ +package com.baeldung.caching.ttl; + +public @interface SlowTest { +} \ No newline at end of file diff --git a/spring-caching-2/src/test/resources/application.properties b/spring-caching-2/src/test/resources/application.properties new file mode 100644 index 0000000000..13fc375261 --- /dev/null +++ b/spring-caching-2/src/test/resources/application.properties @@ -0,0 +1,15 @@ +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + +# Enabling H2 Console +spring.h2.console.enabled=true +spring.h2.console.path=/h2 +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=false +caching.spring.hotelListTTL=43200 +# Connection details +#spring.redis.host=localhost +#spring.redis.port=6379 +server.port=8000 \ No newline at end of file diff --git a/spring-caching-2/ttl/pom.xml b/spring-caching-2/ttl/pom.xml deleted file mode 100644 index b7edf90c44..0000000000 --- a/spring-caching-2/ttl/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - spring-caching-3 - 0.1-SNAPSHOT - spring-caching-3 - - - org.springframework.boot - spring-boot-starter-parent - 2.3.4.RELEASE - - - - - org.springframework.data - spring-data-commons - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-validation - - - com.h2database - h2 - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - - com.google.guava - guava - 30.0-jre - - - \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/config/GuavaCachingConfig.java b/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/config/GuavaCachingConfig.java deleted file mode 100644 index bfd0c6ce1e..0000000000 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/config/GuavaCachingConfig.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.caching.ttl.config; - -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.TimeUnit; - -public class GuavaCachingConfig { - - private Cache cache; - - Logger logger = LoggerFactory.getLogger(GuavaCachingConfig.class); - - public GuavaCachingConfig(int expiryDuration, TimeUnit timeUnit) { - cache = CacheBuilder.newBuilder() - .expireAfterWrite(expiryDuration, timeUnit) - .concurrencyLevel(Runtime.getRuntime().availableProcessors()) - .build(); - } - - public T get(Long key) { - return cache.getIfPresent(key); - } - - public void add(Long key, T value) { - if(key != null && value != null) { - cache.put(key, value); - logger.info( - String.format("A %s record stored in Cache with key: %s", value.getClass().getSimpleName(), key)); - } - } -} \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/GuavaCacheCustomizer.java b/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/GuavaCacheCustomizer.java deleted file mode 100644 index c64f0ea5f5..0000000000 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/GuavaCacheCustomizer.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.caching.ttl.service; - -import com.baeldung.caching.ttl.config.GuavaCachingConfig; -import com.baeldung.caching.ttl.model.Hotel; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.stereotype.Component; - -import java.util.concurrent.TimeUnit; - -@Component -public class GuavaCacheCustomizer { - - @Value("${caching.guava.hotelItemTTL}") - Integer hotelItemTTL; - - @Bean - public GuavaCachingConfig hotelGuavaCacheStore() { - return new GuavaCachingConfig<>(hotelItemTTL, TimeUnit.MILLISECONDS); - } -} \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/HotelService.java b/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/HotelService.java deleted file mode 100755 index c69d371456..0000000000 --- a/spring-caching-2/ttl/src/main/java/com/baeldung/caching/ttl/service/HotelService.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.caching.ttl.service; - -import com.baeldung.caching.ttl.repository.HotelRepository; -import com.baeldung.caching.ttl.config.GuavaCachingConfig; -import com.baeldung.caching.ttl.exception.ElementNotFoundException; -import com.baeldung.caching.ttl.model.Hotel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cache.annotation.CacheEvict; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class HotelService { - - private final HotelRepository hotelRepository; - private final GuavaCachingConfig hotelGuavaCachingConfig; - Logger logger = LoggerFactory.getLogger(HotelService.class); - - HotelService(HotelRepository hotelRepository, GuavaCachingConfig hotelGuavaCachingConfig) { - this.hotelRepository = hotelRepository; - this.hotelGuavaCachingConfig = hotelGuavaCachingConfig; - } - - @Cacheable("hotels") - public List getAllHotels() { - return hotelRepository.getAllHotels(); - } - - @CacheEvict(value = "hotels", allEntries = true) - @Scheduled(fixedRateString = "${caching.spring.hotelListTTL}") - public void emptyHotelsCache() { - logger.info("emptying Hotels cache"); - } - - - public Hotel getHotelById(Long hotelId) { - if (hotelGuavaCachingConfig.get(hotelId) != null) { - logger.info(String.format("hotel with id: %s found in cache", hotelId)); - return hotelGuavaCachingConfig.get(hotelId); - } - logger.info(String.format("hotel with id: %s is being searched in DB", hotelId)); - Hotel hotel = hotelRepository.getHotelById(hotelId) - .orElseThrow(() -> new ElementNotFoundException(String.format("Hotel with id %s not found", hotelId))); - hotelGuavaCachingConfig.add(hotelId, hotel); - return hotel; - } - -} \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/resources/application.yml b/spring-caching-2/ttl/src/main/resources/application.yml deleted file mode 100644 index 8f45cc140d..0000000000 --- a/spring-caching-2/ttl/src/main/resources/application.yml +++ /dev/null @@ -1,15 +0,0 @@ -spring: - jpa: - open-in-view: true - hibernate: - ddl-auto: create-drop - show-sql: false - -server: - port: 8000 - -caching: - spring: - hotelListTTL: 43200 - guava: - hotelItemTTL: 43200 \ No newline at end of file diff --git a/spring-caching-2/ttl/src/main/resources/data.sql b/spring-caching-2/ttl/src/main/resources/data.sql deleted file mode 100644 index 6b2250be00..0000000000 --- a/spring-caching-2/ttl/src/main/resources/data.sql +++ /dev/null @@ -1,36 +0,0 @@ -SET REFERENTIAL_INTEGRITY FALSE; -TRUNCATE TABLE city; -TRUNCATE TABLE hotel; -SET REFERENTIAL_INTEGRITY TRUE; -ALTER TABLE city - ALTER COLUMN id RESTART WITH 1; -ALTER TABLE hotel - ALTER COLUMN id RESTART WITH 1; - -INSERT INTO city(id, name, city_centre_latitude, city_centre_longitude) -VALUES (1, 'Amsterdam', 52.368780, 4.903303); -INSERT INTO city(id, name, city_centre_latitude, city_centre_longitude) -VALUES (2, 'Manchester', 53.481062, -2.237706); - -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('Monaghan Hotel', false, 9.2, 1, 'Weesperbuurt en Plantage', 52.364799, 4.908971); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('The Thornton Council Hotel', false, 6.3, 1, 'Waterlooplein', 52.3681563, 4.9010029); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('McZoe Trescothiks Hotel', false, 9.8, 1, 'Oude Stad, Harlem', 52.379577, 4.633547); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('Stay Schmtay Hotel', false, 8.7, 1, 'Jan van Galenstraat', 52.3756755, 4.8668628); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('Fitting Image Hotel', false, NULL, 1, 'Staatsliedenbuurt', 52.380936, 4.8708297); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('Raymond of Amsterdam Hotel', false, NULL, 1, '22 High Avenue', 52.3773989, 4.8846443); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('201 Deansgate Hotel', false, 7.3, 2, '201 Deansgate', 53.4788305, -2.2484721); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('Fountain Street Hotel', true, 3.0, 2, '35 Fountain Street', 53.4811298, -2.2402227); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('Sunlight House', false, 4.3, 2, 'Little Quay St', 53.4785129, -2.2505943); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('St Georges House', false, 9.6, 2, '56 Peter St', 53.477822, -2.2462002); -INSERT INTO hotel(name, deleted, rating, city_id, address, latitude, longitude) -VALUES ('Marriot Bonvoy', false, 9.6, 1, 'Hans Zimmerstraat', 53.477872, -2.2462003); \ No newline at end of file diff --git a/spring-caching-2/ttl/src/test/java/com/baeldung/caching/ttl/controller/HotelControllerIntegrationTest.java b/spring-caching-2/ttl/src/test/java/com/baeldung/caching/ttl/controller/HotelControllerIntegrationTest.java deleted file mode 100644 index 821e7341c8..0000000000 --- a/spring-caching-2/ttl/src/test/java/com/baeldung/caching/ttl/controller/HotelControllerIntegrationTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.caching.ttl.controller; - -import com.baeldung.caching.ttl.model.Hotel; -import com.baeldung.caching.ttl.repository.CityRepository; -import com.baeldung.caching.ttl.repository.HotelRepository; -import com.booking.testing.SlowTest; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.test.web.servlet.MockMvc; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@ExtendWith(SpringExtension.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@AutoConfigureMockMvc -@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:data.sql") -@SlowTest -class HotelControllerIntegrationTest { - @Autowired private MockMvc mockMvc; - @Autowired private ObjectMapper mapper; - - @Autowired private HotelRepository repository; - @Autowired private CityRepository cityRepository; - - @Test - @DisplayName("When all hotels are requested then they are all returned") - void whenAllHotelsRequested_thenReturnAllHotels() throws Exception { - mockMvc - .perform(get("/hotel")) - .andExpect(status().is2xxSuccessful()) - .andExpect(jsonPath("$", hasSize((int) repository.findAll().stream().count()))); - } - - @Test - @DisplayName("When a hotel is requested by id then the hotel is returned") - void whenAGivenHotelsRequested_thenReturnTheHotel() throws Exception { - Long hotelId = 1L; - Hotel hotel = - mapper - .readValue( - mockMvc - .perform( - get("/hotel/" + hotelId) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andReturn() - .getResponse() - .getContentAsString(), - Hotel.class); - - assertThat( - repository - .findById(hotelId) - .orElseThrow(() -> new IllegalStateException(String - .format("Hotel with id %s does not exist even in repository", hotelId))), - equalTo(hotel)); - } -} \ No newline at end of file diff --git a/spring-caching-2/ttl/src/test/java/com/booking/testing/SlowTest.java b/spring-caching-2/ttl/src/test/java/com/booking/testing/SlowTest.java deleted file mode 100644 index 20a9ceb8ec..0000000000 --- a/spring-caching-2/ttl/src/test/java/com/booking/testing/SlowTest.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.booking.testing; - -public @interface SlowTest { -} \ No newline at end of file diff --git a/spring-caching-2/ttl/src/test/resources/application.yml b/spring-caching-2/ttl/src/test/resources/application.yml deleted file mode 100644 index a7836fc5da..0000000000 --- a/spring-caching-2/ttl/src/test/resources/application.yml +++ /dev/null @@ -1,15 +0,0 @@ -server: - port: 8001 - -spring: - jpa: - open-in-view: true - hibernate: - ddl-auto: create-drop - show-sql: false - -caching: - spring: - hotelListTTL: 43200 - guava: - hotelItemTTL: 43200 \ No newline at end of file