简体   繁体   中英

Memcached + SpringBoot read cache key value from a constant file

I wanna read memcached key from a java constant file while caching and evicting data. I don't wanna read from a property file, just read from a constant file.

For example while caching data:

BookConstant.java

public class BookConstant
{
    public static final String CACHE_BY_BOOK_ID = "book_id";
}

BookServiceImpl.java

@Override
@Cacheable(cacheNames = BookConstant.CACHE_NAME, key = "#BookConstant.CACHE_BY_BOOK_ID + '_' + #id")
public Book getById(Long id)
{
    Optional<Book> book = bookRepository.findById(id);
    return book.orElse(null);
}

My purpose is generate key :

book_id_1234

And while evicting data:

@Override
public Book updateBook(Book book)
{
    book.setModifiedDate(new Date());
    Book newBook = bookRepository.save(book);

    bookSearchService.insertBookIndex(newBook);

    memcachedClient.evict(BookConstant.CACHE_BY_BOOK_ID + "_" + book.getId());

    return newBook;
}

So it's throwing error while caching data:

SpelEvaluationException: EL1007E: Property or field 'CACHE_BY_BOOK_ID' cannot be found on null

Because it tries read key from a property file.

I'm not sure is possible or not read key from a constant file as dynamically, but that's the problem. If it's possible, can you help me please? Thanks.

The SpEL for accessing the constant value used in @Cacheable annotation is incorrect. You need to specify the full class name, with the package eg if your package is com.example then specify it like this:

@Cacheable(cacheNames = BookConstant.CACHE_NAME, key = "T(com.example.BookConstant).CACHE_BY_BOOK_ID + '_' + #id")
public Book getById(Long id) {
    //...
}

For the update, you don't need to evict using the memcachedClient directly, but instead use the @CacheEvict annotation eg

@CacheEvict(cacheNames = BookConstant.CACHE_NAME, key = "T(com.example.BookConstant).CACHE_BY_BOOK_ID + '_' + #book.id")
public Book updateBook(Book book) {
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM