All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.springboot.memcached.config.MemcachedAutoConfiguration Maven / Gradle / Ivy

There is a newer version: 1.0.1
Show newest version
package com.springboot.memcached.config;

import net.spy.memcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;

/**
 * @Author:txxs
 * @Date: 2017/6/16
 * @Time:11:35
 */
@Configuration
public class MemcachedAutoConfiguration{
    private static final String LOCALHOST = "localhost";
    private static final int DEFAULT_PORT = 11211;
    @Autowired
    private Environment environment;

    public MemcachedAutoConfiguration() {
    }

    @Bean
    public MemcachedClient memcachedClient() throws IOException {
        ArrayList addresses = new ArrayList();
        String servers = this.environment.getProperty("memcached.servers");
        if(StringUtils.isEmpty(servers)) {
            addresses.add(new InetSocketAddress("localhost", 11211));
        } else {
            String[] serverArray = servers.split(",");
            int length = serverArray.length;

            for(int i = 0; i < length; ++i) {
                String server = serverArray[i];
                int colon = server.indexOf(":");
                if(colon == -1) {
                    addresses.add(new InetSocketAddress(server, 11211));
                } else {
                    int port = Integer.parseInt(server.substring(colon + 1));
                    addresses.add(new InetSocketAddress(server.substring(0, colon), port));
                }
            }
        }

        return new MemcachedClient(addresses);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy