user3133300
user3133300

Reputation: 627

Spring Redis Cache not evicting

The following works (results in the evict being performed):

fooController {
    @ApiEndpoint
    public delete(id) {
        fooService.deleteFoo(id)
    }
}

fooService {
    @CacheEvict(value = "cache1", key = "#id")
    public void deleteFoo(Long id) {
        //delete logic here
    }
}

But this does not work (nothing is evicted from the cache):

fooController {
    @ApiEndpoint
    public delete(name) {
        fooService.deleteFoo2(name)
    }
}

fooService {
    public void deleteFoo2(String name) {
        //delete logic here
        deleteFoo(name.getId())
    }

    @CacheEvict(value = "cache1", key = "#id")
    public void deleteFoo(Long id) {
        //delete logic here
    }
}

Why are my @CacheEvict annotations only called when the method is called straight from the controller?

I'm using Redis as the caching mechanism.

Upvotes: 1

Views: 819

Answers (2)

Zon
Zon

Reputation: 19918

To make spring aspect intercept @Cache* annotations you have to make external call. If you don't like to call this method from another object, use bean self-invocation approach. In this case your class is presented as two objects and one calls the other:

@Resource private FooController thisBean;

public delete(id) {
  thisBean.deleteFoo(id)
}

@CacheEvict(value = "cache1", key = "#id")
public void deleteFoo(Long id) {}

Upvotes: 0

Jet
Jet

Reputation: 93

Aop is not worinking when your method is called inside the class. It is working when method is called by another class. So you can define deleteFoo in another service.

Upvotes: 3

Related Questions