java.lang.NullPointerException: 使用 Gemfire cachewriter 保存 jpa 数据时

java.lang.NullPointerException: When saving jpa data using Gemfire cachewriter

Jpa 存储库保存在所有 类 中工作。但是当试图在 CacheWriter 中保存时,它会抛出 NullPointerException(personRepository.save(entryEvent.getNewValue()))。对此有什么想法吗?在应用程序属性中配置了 mysql 数据库。

java.lang.NullPointerException
    at com.javasampleapproach.gemfirerestapi.GemfireWriter.beforeCreate(GemfireWriter.java:28)
    at com.gemstone.gemfire.internal.cache.LocalRegion.cacheWriteBeforePut(LocalRegion.java:3131)
    at com.gemstone.gemfire.internal.cache.AbstractRegionMap.invokeCacheWriter(AbstractRegionMap.java:3145)
    at com.gemstone.gemfire.internal.cache.AbstractRegionMap.basicPut(AbstractRegionMap.java:2909)
    at com.gemstone.gemfire.internal.cache.LocalRegion.virtualPut(LocalRegion.java:5821)
    at com.gemstone.gemfire.internal.cache.LocalRegionDataView.putEntry(LocalRegionDataView.java:118)
    at com.gemstone.gemfire.internal.cache.LocalRegion.basicPut(LocalRegion.java:5211)
    at com.gemstone.gemfire.internal.cache.LocalRegion.validatedPut(LocalRegion.java:1597)
    at com.gemstone.gemfire.internal.cache.LocalRegion.put(LocalRegion.java:1580)
    at com.gemstone.gemfire.internal.cache.AbstractRegion.put(AbstractRegion.java:327)

控制器:

@GetMapping(value = "/getPerson")
    public Iterable<Person> getPerson(@RequestParam("id") long personId,@RequestParam("age") int age, @RequestParam("name") String name) {
        try{
            Person bob = new Person();
            bob.setPersonId(personId);
            bob.setAge(age);
            bob.setName(name);
            Region<Long,Person> region=gemfireCache.getRegion("person");
            region.put(personId, bob);

        }catch(Exception e){
            e.printStackTrace();
        }
        return personRepository.findAll();
    }

缓存编写器:

public class GemfireCacheWriter implements CacheWriter<Long, Person>{
    @Autowired
    PersonRepository personRepository;

   @Override
    public void beforeCreate(EntryEvent<Long, Person> entryEvent) throws CacheWriterException {
        // TODO Auto-generated method stub
        personRepository.save(entryEvent.getNewValue());
    }

    }

缓存写入器配置:

@Bean
    LocalRegionFactoryBean<Long, Person> personRegion(final GemFireCache cache) {
        LocalRegionFactoryBean<Long, Person> personRegion = new LocalRegionFactoryBean<>();
        personRegion.setCache(cache);
        personRegion.setName("person");
        personRegion.setPersistent(false);
        personRegion.setCacheWriter(new GemfireWriter());
        personRegion.setCacheLoader(new GemfireLoader());
        return personRegion;
    }

查看 LocalRegion 的源代码,我不认为你的 CacheWriter 收到的 entryEvent 可能是 null,所以实际的 null参考大概是personRepository。您是否正确配置 spring-data-gemfire 以自动装配 PersonRepositoryCacheWriter 是否配置为 Spring bean(以 @Component 为例)?。

您可以使用 Write Through Example 作为实现此用例的良好起点。

希望这对您有所帮助。干杯。