使用 NCache 作为 Spring 数据缓存

NCache作为内存中、极快且可扩展的分布式缓存,它提供与 Spring 的集成,通过减少昂贵的数据传输来提高应用程序性能。

Spring是Java的轻量级依赖注入和面向方面的开发容器和框架。 它可以让您简化应用程序开发并在应用程序中插入可重用的部分,例如 NCache.

 

为什么将您的 Spring 应用程序与 NCache?

Spring 本身通过提供内聚性和松散耦合来降低 Java 开发的整体复杂性,但它会在这些应用程序中产生高流量。 这些高流量的 Spring 应用程序面临着严重的可扩展性问题。 因此,满足其可扩展性要求的内存分布式缓存至关重要。

尽管这些应用程序可以通过向其服务器场添加更多服务器来进行扩展,但不幸的是,数据库无法扩展以处理如此高的负载。 对于这些场景,分布式缓存最适合处理数据库 可扩展性 问题。

因此,最好的选择是 NCache。 这是一个快速的、内存中的、 键值存储 分布式缓存,它实现了 Spring 缓存模块,使您的 Spring 应用程序具有可扩展性和分布式性。 它通过减少导致可扩展性问题的昂贵数据库行程来减轻数据库负担,并提供更快的性能。

 

如何配置 Spring 应用程序以使用 NCache

NCache 通过以下两种方式提供 Spring 缓存支持:

  • 通过 Spring 缓存提供者, NCache 充当 Spring 应用程序的缓存管理器。
  • 通过 JCache 缓存提供程序, NCache 使用 JCache 支持的特性。
 

添加依赖项

为了配置 Spring 应用程序,首先,您必须添加 Spring 和 NCache 提供。

<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <artifactId>ncache-spring</artifactId>
    <version>x.x.x</version>
</dependency>
 

通过 Spring Caching Provider 配置 Spring 应用程序

添加这些依赖项后,通过基于 Java 或基于 XML 的 Bean 定义在 Spring 应用程序中定义 Bean。

基于Java的Bean定义:
要使用基于 Java 的定义来定义 bean,您需要添加 @豆角,扁豆 CachingConfiguration 类中的注释,其中 setConfigFile 方法将指定您的路径 ncache-spring.xml 文件。 有关详细信息,请参阅 基于Java的Bean 定义。

@Configuration
class CachingConfiguration {
    @Bean
    public CacheManager cacheManager() {
        String resource = Path.of(System.getenv("NCHOME"), "config/ncache-spring.xml").toString();

        SpringConfigurationManager springConfigurationManager = new SpringConfigurationManager();
        springConfigurationManager.setConfigFile(resource);

        NCacheCacheManager cacheManager = new NCacheCacheManager();
        cacheManager.setSpringConfigurationManager(springConfigurationManager);

        return cacheManager;
    }
}

基于 XML 的 Bean 定义:
要使用基于 XML 的定义来定义 bean,您需要添加一个启用缓存并指定的 XML 文件 NCache 作为缓存管理器。 你必须为cacheManager和 NCache配置管理器。 此外,您必须为 cacheManager 指定以下属性。

  • 弹簧配置管理器: 参考 NCache 配置管理器 bean。
  • 日志文件路径: 缓存管理器日志的完全限定路径。
<bean id="cacheManager" class="com.alachisoft.integrations.spring.NCacheCacheManager">
	<property name="springConfigurationManager" ref="NCacheConfigurationManager"/>
	<property name="logFilePath" value=" C:\Program Files\NCache\log-files\CustomerDBSpringLogs"/>
</bean>
<bean id="NCacheConfigurationManager" class="com.alachisoft.integrations.spring.configuration.SpringConfigurationManager">
        <property name="configFile" value="ncache-spring.xml">
</bean>

有关详细信息,请访问 基于 XML 的 Bean 定义.

此外,您必须在 ncache-spring.xml 文件 NCache 管理中心。 每个缓存都需要自己的定义以及该文件中自己的一组属性。 例如:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application-config default-cache-name="books">
  <caches>
    <cache name="books" ncacheid-instance="democache" priority="normal" expiration-type="absolute" expiration-period="300"/>
  </caches>
</application-config>
 

通过 JCache Caching Provider 配置 Spring Applications

Spring 还支持兼容 JCache 的缓存提供程序,您可以在 Spring 应用程序中使用 JCache NCache。 首先,为Spring添加Maven依赖, NCache和 JCache。 添加依赖后,配置缓存:

  • 地址 spring.cache.cache 名称 标签在 应用程序属性 文件。 缓存名称应与配置中的相同 NCache 管理中心.
  • 通过配置缓存 JCacheManager定制器 在运行时使用所需配置初始化缓存的类。

有关更多信息,您可以查看我们的 JCache Spring 文档.

 

识别需要缓存的方法

通过上面定义的两个配置启用缓存后,下一步是将这些缓存行为绑定到它们各自的方法以使用 NCache 作为 Spring 的缓存提供程序。

您可以通过两种方式将缓存行为绑定到它们的方法。 一是通过 缓存注释.

// BookController.java
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    // Get a Spring Service to save objects in the DB. This also caches them with 5min absolute (TTL) expiration.
    BookService service = context.getBean(BookService.class);
    service.save(new Book(18001, "The Second Machine Age", "Erik Brynjolfsson, Andrew McAfee", new Date(2014, 0, 20)));

    // Print all saved books details
    printBooks(service.listAll());

    // Use Spring Service to get a book from the DB. It actually comes from the cache
    Book foundBook = service.findBookByIsbn(18001);
    printBookDetails(foundBook);

    foundBook.setAuthor("New Author");
    Book UpdatedBook = service.update(foundBook);

    printBookDetails(UpdatedBook);
    context.close();
    System.exit(0);
    }

// BookService.java
@Service
class BookService {
    @Autowired
    private BookRepository repo;

    public List<Book> listAll() {
        return repo.findAll();
    }

    @CachePut(value = "demoCache", key = "#book.getISBN()")
    public Book save(Book book) { return repo.save(book); }

    @CachePut(value = "demoCache", key = "#book.getISBN()")
    public Book update(Book book) { return repo.save(book); }

    @Cacheable(value = "demoCache", key = "#id")
    public Book get(int id) {
        return repo.findById(id);
    }

    @Cacheable(value = "demoCache", key = "#isbn")
    public Book findBookByIsbn(long isbn) {
        return repo.findBookByIsbn(isbn);
    }

    @CacheEvict(value = "demoCache", allEntries = true)
    public void delete(int id) {
        repo.deleteById(id);
    }
}

如果你不使用注释,那么 基于 XML 的声明式缓存 可以在您可以在外部指定目标方法和缓存指令的地方使用。

<!-- the service we want to make cacheable -->
<bean id="bookService" class="x.y.service.BookService"/>
<!-- cache definitions -->
<cache:advice id="booksCacheAdvice" cache-manager="cacheManager">
    <cache:caching cache="demoCache">
        <cache:cacheable method="getBookNameByIsbn" key="#isbn"/>
        <cache:cache-evict method="loadBooks" all-entries="true"/>
    </cache:caching>
</cache:advice>

接下来做什么?

联系我们

联系电话
©版权所有 Alachisoft 2002 - 版权所有。 NCache 是 Diyatech Corp. 的注册商标。