Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,11 @@ class OwnerController {

private final OwnerRepository owners;

public OwnerController(OwnerRepository owners) {
private final OwnerDirectorySynchronizer ownerDirectorySynchronizer;

public OwnerController(OwnerRepository owners, OwnerDirectorySynchronizer ownerDirectorySynchronizer) {
this.owners = owners;
this.ownerDirectorySynchronizer = ownerDirectorySynchronizer;
}

@InitBinder
Expand Down Expand Up @@ -82,6 +85,7 @@ public String processCreationForm(@Valid Owner owner, BindingResult result, Redi
}

this.owners.save(owner);
this.ownerDirectorySynchronizer.ownerAggregateChanged();
redirectAttributes.addFlashAttribute("message", "New Owner Created");
return "redirect:/owners/" + owner.getId();
}
Expand Down Expand Up @@ -157,6 +161,7 @@ public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @

owner.setId(ownerId);
this.owners.save(owner);
this.ownerDirectorySynchronizer.ownerAggregateChanged();
redirectAttributes.addFlashAttribute("message", "Owner Values Updated");
return "redirect:/owners/{ownerId}";
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;

import org.springframework.samples.petclinic.system.CacheOperations;
import org.springframework.stereotype.Service;

/**
* Keeps front-desk owner-directory projections synchronized after aggregate changes.
*/
@Service
public class OwnerDirectorySynchronizer {

private final CacheOperations cacheOperations;

public OwnerDirectorySynchronizer(CacheOperations cacheOperations) {
this.cacheOperations = cacheOperations;
}

public void ownerAggregateChanged() {
this.cacheOperations.evict(this.cacheOperations.ownerSearchCache());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.samples.petclinic.system.CacheOperations;

/**
* Repository class for <code>Owner</code> domain objects. All method names are compliant
Expand All @@ -42,6 +44,7 @@ public interface OwnerRepository extends JpaRepository<Owner, Integer> {
* @return a Collection of matching {@link Owner}s (or an empty Collection if none
* found)
*/
@Cacheable(CacheOperations.OWNER_SEARCH_CACHE)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound the owner-search cache

Each distinct (lastName, Pageable) supplied to GET /owners now creates a permanent cache entry, but the configured Caffeine cache has neither a maximum size nor an expiry policy. Because every entry retains a full page of eager owner/pet/visit aggregates, ordinary varied searches—or requests deliberately using unique search strings and page numbers—can grow the heap without bound until the application is restarted or the entire cache is manually cleared. Configure an eviction limit/TTL or restrict which searches are cached.

Useful? React with 👍 / 👎.

Page<Owner> findByLastNameStartingWith(String lastName, Pageable pageable);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,13 @@ class PetController {

private final PetTypeRepository types;

public PetController(OwnerRepository owners, PetTypeRepository types) {
private final OwnerDirectorySynchronizer ownerDirectorySynchronizer;

public PetController(OwnerRepository owners, PetTypeRepository types,
OwnerDirectorySynchronizer ownerDirectorySynchronizer) {
this.owners = owners;
this.types = types;
this.ownerDirectorySynchronizer = ownerDirectorySynchronizer;
}

@ModelAttribute("types")
Expand Down Expand Up @@ -132,6 +136,7 @@ public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult res
result.rejectValue("name", "duplicate", "already exists");
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
this.ownerDirectorySynchronizer.ownerAggregateChanged();
redirectAttributes.addFlashAttribute("message", "New Pet has been Added");
return "redirect:/owners/{ownerId}";
}
Expand Down Expand Up @@ -174,6 +179,7 @@ public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult resul
result.rejectValue("name", "duplicate", "already exists");
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
this.ownerDirectorySynchronizer.ownerAggregateChanged();
redirectAttributes.addFlashAttribute("message", "Pet details has been edited");
return "redirect:/owners/{ownerId}";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ class VisitController {

private final OwnerRepository owners;

public VisitController(OwnerRepository owners) {
private final OwnerDirectorySynchronizer ownerDirectorySynchronizer;

public VisitController(OwnerRepository owners, OwnerDirectorySynchronizer ownerDirectorySynchronizer) {
this.owners = owners;
this.ownerDirectorySynchronizer = ownerDirectorySynchronizer;
}

@InitBinder
Expand Down Expand Up @@ -107,6 +110,7 @@ public String processNewVisitForm(@ModelAttribute Owner owner, @PathVariable int

owner.addVisit(petId, visit);
this.owners.save(owner);
this.ownerDirectorySynchronizer.ownerAggregateChanged();
redirectAttributes.addFlashAttribute("message", "Your visit has been booked");
return "redirect:/owners/{ownerId}";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ class CacheConfiguration {

@Bean
public JCacheManagerCustomizer petclinicCacheConfigurationCustomizer() {
return cm -> cm.createCache("vets", cacheConfiguration());
return cm -> {
cm.createCache("vets", cacheConfiguration());
cm.createCache(CacheOperations.OWNER_SEARCH_CACHE, cacheConfiguration());
};
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.system;

import java.util.Map;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Lightweight operational endpoints for checking and refreshing owner-search data.
*/
@RestController
@RequestMapping("/manage/cache/owner-search")
class CacheDiagnosticsController {

private final CacheOperations cacheOperations;

CacheDiagnosticsController(CacheOperations cacheOperations) {
this.cacheOperations = cacheOperations;
}

@GetMapping
CacheOperations.CacheStatus status() {
return this.cacheOperations.ownerSearchStatus();
}

@DeleteMapping
Map<String, Object> evict() {
boolean evicted = this.cacheOperations.evictOwnerSearch();
return Map.of("cache", CacheOperations.OWNER_SEARCH_CACHE, "evicted", evicted);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.system;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

/**
* Operational boundary for inspecting and invalidating application caches.
*/
@Service
public class CacheOperations {

public static final String OWNER_SEARCH_CACHE = "ownerSearch";

private final CacheManager cacheManager;

public CacheOperations(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}

/**
* Invalidate all cached owner-directory searches.
* @return {@code true} when the configured cache was available
*/
public boolean evictOwnerSearch() {
return evict(ownerSearchCache());
}

/**
* Evict every entry from the supplied cache.
* @param cache the cache selected by the caller
* @return {@code true} when a cache was supplied
*/
public boolean evict(Cache cache) {
if (cache == null) {
return false;
}
cache.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Prevent stale searches from repopulating after eviction

When a cache-miss search overlaps a mutation, the search can read the old database state, the mutation can commit and execute this clear, and the search's @Cacheable interceptor can then publish its old Page after the clear has completed. That stale result remains indefinitely because the cache has no expiry and no further invalidation is guaranteed, so the synchronous clear does not actually ensure fresh searches under concurrent requests. Use a generation/versioned key or otherwise coordinate cache population with writes.

Useful? React with 👍 / 👎.

return true;
}

/**
* Report whether the owner-search cache is currently available.
*/
public CacheStatus ownerSearchStatus() {
return new CacheStatus(OWNER_SEARCH_CACHE, ownerSearchCache() != null);
}

/**
* Resolve the cache used by the owner directory.
*/
public Cache ownerSearchCache() {
return this.cacheManager.getCache(OWNER_SEARCH_CACHE);
}

public record CacheStatus(String name, boolean available) {
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ class OwnerControllerTests {
@MockitoBean
private OwnerRepository owners;

@MockitoBean
private OwnerDirectorySynchronizer ownerDirectorySynchronizer;

private Owner george() {
Owner george = new Owner();
george.setId(TEST_OWNER_ID);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;

import org.junit.jupiter.api.Test;
import org.springframework.cache.Cache;
import org.springframework.samples.petclinic.system.CacheOperations;

import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

class OwnerDirectorySynchronizerTests {

@Test
void ownerAggregateChangesInvalidateCachedSearches() {
CacheOperations cacheOperations = mock(CacheOperations.class);
Cache ownerSearchCache = mock(Cache.class);
given(cacheOperations.ownerSearchCache()).willReturn(ownerSearchCache);
OwnerDirectorySynchronizer synchronizer = new OwnerDirectorySynchronizer(cacheOperations);

synchronizer.ownerAggregateChanged();

verify(cacheOperations).evict(ownerSearchCache);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ class PetControllerTests {
@MockitoBean
private PetTypeRepository types;

@MockitoBean
private OwnerDirectorySynchronizer ownerDirectorySynchronizer;

@BeforeEach
void setup() {
PetType cat = new PetType();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ class VisitControllerTests {
@MockitoBean
private OwnerRepository owners;

@MockitoBean
private OwnerDirectorySynchronizer ownerDirectorySynchronizer;

@BeforeEach
void init() {
Owner owner = new Owner();
Expand Down
Loading
Loading