Skip to content

Commit

Permalink
Merge pull request smallrye#739 from aureamunoz/custom-expiration-sni…
Browse files Browse the repository at this point in the history
…ppet

Add custom expiration policy for cache snippet to the doc
  • Loading branch information
aureamunoz authored Dec 19, 2023
2 parents f061d3f + cf70d93 commit 5bcd926
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
8 changes: 7 additions & 1 deletion docs/docs/service-discovery/custom-service-discovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,10 @@ If you want to customize the expiration strategy, you need:
1. Implement the `cache` method where the expiration strategy should be defined.
2. Invalidate the cache when expiration condition evaluates to true.

Take a look to the [Kubernetes Service Discovery](kubernetes.md#Caching the service instances) for further details about this feature.
Look at the example bellow:

```java linenums="1"
{{ insert('examples/CustomExpirationCachedAcmeServiceDiscovery.java') }}
```

Additionally, you can check the [Kubernetes Service Discovery](kubernetes.md#Caching the service instances) for further details about an event-based invalidation example.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package examples;

import io.smallrye.mutiny.Uni;
import io.smallrye.stork.api.ServiceInstance;
import io.smallrye.stork.impl.CachingServiceDiscovery;
import io.smallrye.stork.impl.DefaultServiceInstance;
import io.smallrye.stork.utils.ServiceInstanceIds;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class CustomExpirationCachedAcmeServiceDiscovery extends CachingServiceDiscovery {

private final String host;
private final int port;

private AtomicBoolean invalidated = new AtomicBoolean();

public CustomExpirationCachedAcmeServiceDiscovery(CachedAcmeConfiguration configuration) {
super(configuration.getRefreshPeriod());
this.host = configuration.getHost();
this.port = Integer.parseInt(configuration.getPort());
}

@Override
public Uni<List<ServiceInstance>> fetchNewServiceInstances(List<ServiceInstance> previousInstances) {
// Retrieve services...
DefaultServiceInstance instance =
new DefaultServiceInstance(ServiceInstanceIds.next(), host, port, false);
return Uni.createFrom().item(() -> Collections.singletonList(instance));
}

@Override
public Uni<List<ServiceInstance>> cache(Uni<List<ServiceInstance>> uni) {
return uni.memoize().until(() -> invalidated.get());
}

//command-based cache invalidation: user triggers the action to invalidate the cache.
public void invalidate() {
invalidated.set(true);
}

}

0 comments on commit 5bcd926

Please sign in to comment.