Search code examples
spring-bootspring-data-gemfire

How to implement a GemFire CacheListener in Spring Boot using Spring Boot for Pivotal GemFire Starter


May I know how to implement a GemFire/Geode CacheListener in my Spring Boot application?

I want to detect delete and update in my "People" Region. I using org.springframework.data:spring-data-gemfire dependency in Maven. Do I need to include any annotation?

@SpringBootApplication  
@ClientCacheApplication(name = "AccessingDataGemFireApplication", logLevel = "error")
@EnableEntityDefinedRegions(basePackageClasses = People.class)
@EnableGemfireRepositories  
public class Application
{
....
}

Solution

  • Since you are using the more convenient @EnableEntityDefinedRegions SDG annotation (which is recommended, especially for simple UC), then you do not explicitly define a Region bean definition (e.g. using SDG's ReplicationRegionFactoryBean or PartitionedRegionFactoryBean classes) as Juan Ramos did in his answer.

    In this case, you can declare a RegionConfigurer to modify the "People" Region and then apply the same technique Juan did from his answer to supply the CacheListener.

    For example:

    @SpringBootApplication
    @EnableEntityDefinedRegions(basePackageClasses = People.class)
    @EnableGemfireRepositories(..)
    class MySpringBootGemFireApplication {
    
      @Bean
      RegionConfigurer peopleRegionConfigurer(
          CacheListener<Long, Person> peopleRegionListener) {
    
        return new RegionConfigurer() {
    
          @Override
          public void configure(String beanName, 
              ClientRegionFactoryBean<Long, Person> regionFactory) {
    
            regionFactoryBean.setCacheListeners(
              new CacheListener[] { peopleRegionListener });
        };
      }
    
      @Bean
      CacheListenerAdapter<Long, Person> peopleRegionListener() {
    
        return new CacheListenerAdapter<>() {
    
            public void afterDestroy(EntryEvent<Long, Person> event) { ... }
    
            public void afterUpdate(EntryEvent<Long, Person> event) { ... }
        };
      }
    }
    

    NOTE: when using the Spring Boot, GemFire Starter (org.springframework.geode:spring-gemfire-starter), the @ClientCacheApplication annotation is definitely not required since SBDG auto-configures a ClientCache instance by default (see here).

    NOTE: Additionally, if your application GemfireRepositories are in a sub-package below the main Spring Boot application class, you also do not need to explicitly declare the @EnableGemfireRepositories since SBDG auto-configures the SD Repository infrastructure for you (see here).

    For more information on SDG Configurers, see here.

    Hope this helps.