无法从 Java 引导中获得使用 memcached 的良好示例

Unable to get good example of using memcached from Java boot

我正在使用 java boot 进行开发。现在我已经使用 'EhCache' 进行缓存,Java boot 直接支持它。这是 "in-process" 缓存,即成为您进程的一部分。现在没关系。但是我的服务器将在不久的将来 运行 在多个节点上。因此想切换到 'Memcached' 作为公共缓存层。

在花费大量时间后,我无法从 java 引导中获得使用 Memcached 的良好示例。我查看了接近我要求的“Simple Spring Memcached”。但它仍然给出了以 Spring 方式使用 XML 配置的示例。 Java开机尽量不要使用XML这样的配置。至少我无法将示例快速映射到 java 引导世界。

我想从 java 引导使用 Memcahed(直接或通过缓存抽象层)。如果有人向我指出相关的 java 引导示例,这将为我节省很多时间。

您可以找到一些资料,了解如何使用 Java 配置而不是 XML 文件 here and here 配置 SSM。 基本上,您必须将所有 bean 的定义从 XML 移动到 Java。

我已经接受了@ragnor 给出的答案。但我想我应该 post 这里有一个对我有用的完整示例。

  1. 通过添加@EnableCaching
  2. 确保您的应用程序启用了缓存
  3. POM.xml 应具有以下依赖性:
<dependency>
        <groupId>com.google.code.simple-spring-memcached</groupId>
        <artifactId>spring-cache</artifactId>
        <version>3.6.1</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.simple-spring-memcached</groupId>
        <artifactId>spymemcached-provider</artifactId>
        <version>3.6.1</version>
    </dependency>
  1. 添加配置文件来配置您的 memcached 缓存配置,比如 MySSMConfig.java
@Configuration
@EnableAspectJAutoProxy
@ImportResource("simplesm-context.xml") // This line may or may not be needed,
                                        // not sure
public class SSMConfig 
{
    private String _memcachedHost; //Machine where memcached is running
    private int _memcachedPort;    //Port on which memcached is running

     @Bean
     public CacheManager cacheManager() 
     {
         //Extended manager used as it will give custom-expiry value facility in future if needed
         ExtendedSSMCacheManager ssmCacheManager = new ExtendedSSMCacheManager();

         //We can create more than one cache, hence list
         List<SSMCache>cacheList = new ArrayList<SSMCache>();

         //First cache: Testcache
         SSMCache testCache = createNewCache(_memcachedHost, _memcachedPort, 
                                    "testcache", 5);

         //One more dummy cache
         SSMCache dummyCache = createNewCache(_memcachedHost,_memcachedPort, 
                    "dummycache", 300);

         cacheList.add(testCache);
         cacheList.add(dummyCache);

         //Adding cache list to cache manager
         ssmCacheManager.setCaches(cacheList);

         return ssmCacheManager;
     }


    //expiryTimeInSeconds: time(in seconds) after which a given element will expire
    //
    private SSMCache createNewCache(String memcachedServer, int port, 
                                String cacheName, int expiryTimeInSeconds)
    {
        //Basic client factory to be used. This is SpyMemcached for now.
        MemcacheClientFactoryImpl cacheClientFactory = new MemcacheClientFactoryImpl();

        //Memcached server address parameters
        //"127.0.0.1:11211"
        String serverAddressStr = memcachedServer + ":" + String.valueOf(port);
        AddressProvider addressProvider = new DefaultAddressProvider(serverAddressStr);

        //Basic configuration object
        CacheConfiguration cacheConfigToUse = getNewCacheConfiguration();

        //Create cache factory
        CacheFactory cacheFactory = new CacheFactory();
        cacheFactory.setCacheName(cacheName);
        cacheFactory.setCacheClientFactory(cacheClientFactory);
        cacheFactory.setAddressProvider(addressProvider);
        cacheFactory.setConfiguration(cacheConfigToUse);

        //Get Cache object
        Cache object = null;
        try {
            object = cacheFactory.getObject();
        } catch (Exception e) {

        }

        //allow/disallow remove all entries from this cache!!
        boolean allowClearFlag = false;
        SSMCache ssmCache = new SSMCache(object, expiryTimeInSeconds, allowClearFlag); 

        return ssmCache;

    }

    private CacheConfiguration getNewCacheConfiguration() 
    {
        CacheConfiguration ssmCacheConfiguration = new CacheConfiguration();
        ssmCacheConfiguration.setConsistentHashing(true);
        //ssmCacheConfiguration.setUseBinaryProtocol(true);
        return ssmCacheConfiguration;
    }

}
  1. 好的,我们准备好使用我们配置的缓存。
  2. 其他一些示例方法 class 从缓存中读取和从缓存中删除
@Cacheable(value="dummycache, key="#givenId.concat('-dmy')", unless="#result == null")
    public String getDummyDataFromMemCached(String givenId)
    {
        logger.warn("getDummyDataFromMemCached: Inside DUMMY method to actually get data");
        return "Sample-" + String.valueOf(givenId);
    }
    @CacheEvict(value="dummycache",key="#givenId.concat('-dmy')")
    public void removeDummyDataFromMemCached(String givenId)
    {
        //Do nothing
        return;
    }
  1. 请注意,我们已经为 kache-keys 添加了后缀。由于 Memcached 不支持缓存区,"dummycache" 和 "testcache" 最终不会在单个服务器上保持分离。 (它们可能与其他一些缓存实现保持分离)。因此,为避免冲突,我们将唯一后缀附加到缓存键。

  2. 如果您想缓存自己的对象 class,请确保它们是可序列化的。只需将 class 定义更改为 'XYZ implements Serializable'.

您还可以查看 Memcached Spring Boot 图书馆。它使用 Memcached 实现 Spring 缓存抽象

换句话说,您使用与任何其他 Spring 缓存实现相同的配置和注释。您可以查看here库的使用情况。

Kotlin and Java中也有示例项目。