欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot:memcached

程序员文章站 2022-03-10 20:20:38
...
pom.xml
==========================================
<!-- memecache spymemcached -->
        <dependency>
            <groupId>com.google.code.simple-spring-memcached</groupId>
            <artifactId>spymemcached</artifactId>
            <version>2.8.4</version>
        </dependency>
==========================================
application.properties
==========================================
cache.timeout=2000
cache.url=172.16.30.58:11211
==========================================
MemcachedConfigation.java
==========================================
@Configuration
public class MemcachedConfigation {

//    <bean id="spy-memcached-conf" class="net.spy.memcached.ConnectionFactoryBuilder">
//        <property name="protocol" value="BINARY" />
//        <property name="locatorType" value="CONSISTENT" />
//        <property name="opTimeout" value="#{cacheproperties['cache.timeout']}" />
//    </bean>
    @Bean("spy-memcached-conf")
    public ConnectionFactoryBuilder connectionFactoryBuilder(@Value("${cache.timeout}")int timeout){
        ConnectionFactoryBuilder connectionFactoryBuilder = new ConnectionFactoryBuilder();
        connectionFactoryBuilder.setProtocol(ConnectionFactoryBuilder.Protocol.BINARY);
        connectionFactoryBuilder.setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT);
        connectionFactoryBuilder.setOpTimeout(timeout);
        return connectionFactoryBuilder;
    }

//    <bean id="memcachedClient" class="net.spy.memcached.MemcachedClient"
//    destroy-method="shutdown">
//        <constructor-arg>
//          <bean factory-bean="spy-memcached-conf" factory-method="build"></bean>
//        </constructor-arg>
//        <constructor-arg>
//            <bean class="net.spy.memcached.AddrUtil" factory-method="getAddresses">
//              <constructor-arg value="#{cacheproperties['cache.url']}" />
//            </bean>
//        </constructor-arg>
//    </bean>
    @Bean(name = "memcachedClient", destroyMethod = "shutdown")
    public MemcachedClient memcachedClient(@Qualifier("spy-memcached-conf") ConnectionFactoryBuilder builder,
                                           @Value("${cache.url}")String url) throws IOException {
        MemcachedClient memcachedClient = new MemcachedClient(builder.build(), AddrUtil.getAddresses(url));
        return memcachedClient;
    }
}