Setup Memcached on Heroku

Add memcachedcloud to your project:
heroku addons:add memcachedcloud

1. Setup Memcached Configuration
2. Setup Memcached Service

1. Setup Memcached Configuration

package com.example.cache;

import java.io.IOException;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CacheConfiguration {
	
	@Bean
	public MemcachedClient memcachedCloudConfiguration() {
		try {
		    AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" },
		        new PlainCallbackHandler(System.getenv("MEMCACHEDCLOUD_USERNAME"), System.getenv("MEMCACHEDCLOUD_PASSWORD")));

		    MemcachedClient mc = new MemcachedClient(
		              new ConnectionFactoryBuilder()
		                  .setProtocol(ConnectionFactoryBuilder.Protocol.BINARY)
		                  .setAuthDescriptor(ad).build(),
		          AddrUtil.getAddresses(System.getenv("MEMCACHEDCLOUD_SERVERS")));
		    return mc;
		} catch (IOException ex) {
		    // the Memcached client could not be initialized.
		}
		return null;
	}
}

2. Setup Memcached Service

package com.example.cache;

import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import net.spy.memcached.MemcachedClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import com.example.model.Customer;
import com.example.service.CustomerService;

@Service
@Import({CacheConfiguration.class})
public class CacheCustomerService implements CustomerService{

	@Autowired MemcachedClient memCachedClient;
	
	@Override
	public Customer getCustomerById(BigInteger id) {
		return (Customer) memCachedClient.get(String.valueOf(id));
	}

	@Override
	public void createCustomer(String fn, String ln) {
		memCachedClient.set("customerKey", 3600, new Customer(fn, ln));
	}

	@Override
	public void deleteCustomer(BigInteger id) {
		memCachedClient.delete(String.valueOf(id));
	}

	@Override
	public void createCustomer(Customer newCustomer) {
		memCachedClient.set("customerKey", 3600, newCustomer);
	}	
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: