net.spy.memcached.AddrUtil Java Examples

The following examples show how to use net.spy.memcached.AddrUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExceptionSwallowingMemcachedClient.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Autowired
public ExceptionSwallowingMemcachedClient(GlobalConfigHandler globalConfigHandler, ZkCuratorHandler zkCuratorHandler) throws Exception {
    logger.info("Initializing...");
    Stat stat = zkCuratorHandler.getCurator().checkExists().forPath(ZK_CONFIG_KEY_MEMCACHED_SERVERS_FPATH);
    if (stat != null) 
    {
        ObjectMapper mapper = new ObjectMapper();
        byte[] bytes = zkCuratorHandler.getCurator().getData().forPath(ZK_CONFIG_KEY_MEMCACHED_SERVERS_FPATH);
        MemcacheConfig config = mapper.readValue(bytes,MemcacheConfig.class);
        logger.info(config.toString());
        memcachedClient = new MemcachedClient(new ConnectionFactoryBuilder(new DefaultConnectionFactory()).setOpTimeout(MEMCACHE_OP_TIMEOUT).build(),
                AddrUtil.getAddresses(config.servers));
        logger.info(String.format("MemcachedClient initialized using %s[%s]", ZK_CONFIG_KEY_MEMCACHED_SERVERS, config.servers));
        
        MemCachePeer.initialise(config.servers,config.numClients);
    }

    if (memcachedClient == null) {
        throw new Exception("*Warning* Memcached NOT initialized!");
    }
    globalConfigHandler.addSubscriber(ZK_CONFIG_KEY_MEMCACHED_SERVERS, this);
}
 
Example #2
Source File: CacheHelper.java    From open-rmbt with Apache License 2.0 6 votes vote down vote up
public void initMemcached(String addresses) // addresses: space sep. like 'localhost:11211 10.10.10.10:1234'
{
    if (memcachedClient.get() != null)
        throw new IllegalStateException("memcached already initialized");
    try
    {
        final MemcachedClient _memcachedClient = new MemcachedClient(
                new BinaryConnectionFactory(),
                AddrUtil.getAddresses(addresses));
        _memcachedClient.addObserver(this);
        memcachedClient.set(_memcachedClient);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
 
Example #3
Source File: MemcachedCache.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static MemcachedCache create(final MemcachedCacheConfig config, String memcachedPrefix, int timeToLive) {
    try {
        SerializingTranscoder transcoder = new SerializingTranscoder(config.getMaxObjectSize());
        // always no compression inside, we compress/decompress outside
        transcoder.setCompressionThreshold(Integer.MAX_VALUE);

        OperationQueueFactory opQueueFactory;
        int maxQueueSize = config.getMaxOperationQueueSize();
        if (maxQueueSize > 0) {
            opQueueFactory = new ArrayOperationQueueFactory(maxQueueSize);
        } else {
            opQueueFactory = new LinkedOperationQueueFactory();
        }
        String hostsStr = config.getHosts();
        ConnectionFactory connectionFactory = new MemcachedConnectionFactoryBuilder()
                .setProtocol(ConnectionFactoryBuilder.Protocol.BINARY)
                .setHashAlg(DefaultHashAlgorithm.FNV1A_64_HASH)
                .setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT).setDaemon(true)
                .setFailureMode(FailureMode.Redistribute).setTranscoder(transcoder).setShouldOptimize(true)
                .setOpQueueMaxBlockTime(config.getTimeout()).setOpTimeout(config.getTimeout())
                .setReadBufferSize(config.getReadBufferSize()).setOpQueueFactory(opQueueFactory).build();
        return new MemcachedCache(new MemcachedClient(new MemcachedConnectionFactory(connectionFactory),
                AddrUtil.getAddresses(hostsStr)), config, memcachedPrefix, timeToLive);
    } catch (IOException e) {
        logger.error("Unable to create MemcachedCache instance.", e);
        throw Throwables.propagate(e);
    }
}
 
Example #4
Source File: MemCacheTicketRegistry.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Creates a new instance that stores tickets in the given memcached hosts.
 *
 * @param hostnames                   Array of memcached hosts where each element is of the form host:port.
 * @param ticketGrantingTicketTimeOut TGT timeout in seconds.
 * @param serviceTicketTimeOut        ST timeout in seconds.
 */
public MemCacheTicketRegistry(final String[] hostnames, final int ticketGrantingTicketTimeOut,
                              final int serviceTicketTimeOut) {
    try {
        this.client = new MemcachedClient(AddrUtil.getAddresses(Arrays.asList(hostnames)));
    } catch (final IOException e) {
        throw new IllegalArgumentException("Invalid memcached host specification.", e);
    }
    this.tgtTimeout = ticketGrantingTicketTimeOut;
    this.stTimeout = serviceTicketTimeOut;
}
 
Example #5
Source File: MemCacheTicketRegistry.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/**
     * Creates a new instance that stores tickets in the given memcached hosts.
     *
     * @param hostnames                   Array of memcached hosts where each element is of the form host:port.
     * @param ticketGrantingTicketTimeOut TGT timeout in seconds.
     * @param serviceTicketTimeOut        ST timeout in seconds.
     */
    public MemCacheTicketRegistry(final String[] hostnames, final int ticketGrantingTicketTimeOut,
final int serviceTicketTimeOut) {
        try {
            this.client = new MemcachedClient(AddrUtil.getAddresses(Arrays.asList(hostnames)));
        } catch (final IOException e) {
            throw new IllegalArgumentException("Invalid memcached host specification.", e);
        }
        this.tgtTimeout = ticketGrantingTicketTimeOut;
        this.stTimeout = serviceTicketTimeOut;
    }
 
Example #6
Source File: MemcacheOperatorTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Before
public void setup()
{
  MemcacheStore operatorStore = new MemcacheStore();
  operatorStore.setServerAddresses( AddrUtil.getAddresses("localhost:11211") );
  MemcacheStore testStore = new MemcacheStore();
  testStore.setServerAddresses( AddrUtil.getAddresses("localhost:11211") );
  testFramework = new KeyValueStoreOperatorTest<MemcacheStore>( operatorStore, testStore );
}
 
Example #7
Source File: MemcachePoolMixin.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public void activateService()
    throws Exception
{
    MemcacheConfiguration config = configuration.get();
    expiration = ( config.expiration().get() == null )
                 ? 3600
                 : config.expiration().get();
    String addresses = ( config.addresses().get() == null )
                       ? "localhost:11211"
                       : config.addresses().get();
    Protocol protocol = ( config.protocol().get() == null )
                        ? Protocol.TEXT
                        : Protocol.valueOf( config.protocol().get().toUpperCase() );
    String username = config.username().get();
    String password = config.password().get();
    String authMech = config.authMechanism().get() == null
                      ? "PLAIN"
                      : config.authMechanism().get();

    ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder();
    builder.setProtocol( protocol );
    if( username != null && !username.isEmpty() )
    {
        String[] authType = { authMech };
        AuthDescriptor to = new AuthDescriptor( authType, new PlainCallbackHandler( username, password ) );
        builder.setAuthDescriptor( to );
    }

    client = new MemcachedClient( builder.build(), AddrUtil.getAddresses( addresses ) );
}
 
Example #8
Source File: MemcachedCache.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static List<InetSocketAddress> getResolvedAddrList(String hostsStr) {
    List<InetSocketAddress> addrs = AddrUtil.getAddresses(hostsStr);
    Iterator<InetSocketAddress> addrIterator = addrs.iterator();
    while (addrIterator.hasNext()) {
        if (addrIterator.next().isUnresolved()) {
            addrIterator.remove();
        }
    }
    return addrs;
}
 
Example #9
Source File: SpyMemcacheIT.java    From hibernate-l2-memcached with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    client = new MemcachedClient(AddrUtil.getAddresses("localhost:11211"));
    Properties properties = new Properties();
    PropertiesHelper props = new PropertiesHelper(properties);
    Config config = new Config(props);
    cache = new MemcachedCache("MemcachedCacheTest", new SpyMemcache(client), config);
}
 
Example #10
Source File: MongoDSN.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public static MongoClient	newClient(String server, String user, String pass, String db) throws UnknownHostException{

	MongoClientOptions options = MongoClientOptions
			.builder()
			.readPreference( ReadPreference.secondaryPreferred() )
			.build();

	List<InetSocketAddress> serverList = AddrUtil.getAddresses(server);
	List<ServerAddress> addrs = new ArrayList<ServerAddress>();
		
	Iterator<InetSocketAddress>	it	= serverList.iterator();
	while ( it.hasNext() ){
		InetSocketAddress	isa	= it.next();
		addrs.add( new ServerAddress( isa.getAddress(), isa.getPort() ) );
	}
	
	
	if ( user != null ) {
		MongoCredential cred = MongoCredential.createCredential( user, db, pass.toCharArray() );
		List<MongoCredential> creds = new ArrayList<MongoCredential>();
		creds.add( cred );

		return new MongoClient( addrs, creds, options );
	} else {
		return new MongoClient( addrs, options );
	}

	
}
 
Example #11
Source File: ApiMemcached.java    From iaf with Apache License 2.0 5 votes vote down vote up
public ApiMemcached() {
	AppConstants ac = AppConstants.getInstance();
	String address = ac.getProperty("etag.cache.server", "localhost:11211");
	String username = ac.getProperty("etag.cache.username", "");
	String password = ac.getProperty("etag.cache.password", "");
	int timeout = ac.getInt("etag.cache.timeout", 10);

	List<InetSocketAddress> addresses = AddrUtil.getAddresses(address);

	ConnectionFactoryBuilder connectionFactoryBuilder = new ConnectionFactoryBuilder()
		.setProtocol(Protocol.BINARY)
		.setOpTimeout(timeout)
		.setInitialObservers(Collections.singleton(obs));

	if(addresses.size()  > 1)
		connectionFactoryBuilder.setFailureMode(FailureMode.Redistribute);
	else
		connectionFactoryBuilder.setFailureMode(FailureMode.Retry);

	if(!username.isEmpty())
		connectionFactoryBuilder.setAuthDescriptor(AuthDescriptor.typical(username, password));

	ConnectionFactory cf = connectionFactoryBuilder.build();

	try {
		client = new MemcachedClient(cf, addresses);
		//Fetching a none-existing key to test the connection
		Future<Object> future = client.asyncGet("test-connection");
		future.get(timeout, TimeUnit.MILLISECONDS);
	} catch (Exception e) {
		ConfigurationWarnings.add(log, "Unable to connect to one or more memcached servers.");
	}
}
 
Example #12
Source File: MemcachePOJOOperatorTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Before
public void setup()
{
  store = new MemcacheStore();
  store.setServerAddresses(AddrUtil.getAddresses("localhost:11211") );
}
 
Example #13
Source File: SessionStorageMemcachedImpl.java    From openbd-core with GNU General Public License v3.0 3 votes vote down vote up
public SessionStorageMemcachedImpl(String appName, String _connectionUri) throws Exception {
	super(appName);
	
	this.uri = _connectionUri;
	
	// Are they using a user/pass
	String connectionUri	= _connectionUri.substring( _connectionUri.indexOf("//")+2 );

	memcache	= new MemcachedClient( new BinaryConnectionFactory(), AddrUtil.getAddresses(connectionUri) );
	
	cfEngine.log( "SessionStorageMemcached: Created " + _connectionUri );
}