Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。
Memcached 是“分布式”的内存对象缓存系统,那么就是说,那些不需要“分布”的,不需要共享的,或者干脆规模小到只有一台服务器的应用, memcached不会带来任何好处,相反还会拖慢系统效率,因为网络连接同样需要资源,即使是UNIX本地连接也一样。
需要注意的是,memcached使用内存管理数据,所以它是易失的,当服务器重启,或者memcached进程中止,数据便会丢失,所以 memcached不能用来持久保存数据。
-
Mac 下memcached 的安装与使用
brew install memcached
启动
brew services start memcached
- pom.xml添加依赖
<dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.5.6</version> </dependency> <dependency> <groupId>com.whalin</groupId> <artifactId>Memcached-Java-Client</artifactId> <version>3.0.2</version> </dependency>
- application.yml配置
memcache: servers: 127.0.0.1:11211 failover: true initConn: 100 minConn: 20 maxConn: 1000 maintSleep: 50 nagel: false socketTO: 3000 aliveCheck: true
- 创建Memcached配置文件
@Configuration public class MemcachedConfig { @Value(value = "${memcache.servers}") private String[] servers; @Value(value = "${memcache.failover}") private boolean failover; @Value(value = "${memcache.initConn}") private int initConn; @Value(value = "${memcache.minConn}") private int minConn; @Value(value = "${memcache.maxConn}") private int maxConn; @Value(value = "${memcache.maintSleep}") private int maintSleep; @Value(value = "${memcache.nagel}") private boolean nagel; @Value(value = "${memcache.socketTO}") private int socketTO; @Value(value = "${memcache.aliveCheck}") private boolean aliveCheck; @Bean public SockIOPool pool(){ SockIOPool pool = SockIOPool.getInstance(); pool.setServers(servers); pool.setFailover(failover); pool.setInitConn(initConn); pool.setMinConn(minConn); pool.setMaxConn(maxConn); pool.setMaintSleep(maintSleep); pool.setNagle(nagel); pool.setSocketTO(socketTO); pool.initialize(); return pool; } @Bean public MemCachedClient memCachedClient(){ return new MemCachedClient(); } }
- 测试
@RunWith(SpringRunner.class) @SpringBootTest public class MemcachedTest { @Autowired private MemCachedClient memCachedClient; @Test public void test() throws InterruptedException { memCachedClient.set("a","123"); String value = (String) memCachedClient.get("a"); System.out.println(value); // 3s后过期 memCachedClient.set("b",1, new Date(3000)); Object flag = memCachedClient.get("b"); System.out.println(flag); Thread.sleep(3000); flag = memCachedClient.get("b"); System.out.println(flag); } @Test public void addUser(){
// 对象必须序列化,实现Serializable接口 User user = new User("鹏", "123456"); memCachedClient.set("user", user); User cUser = (User) memCachedClient.get("user"); System.out.println(cUser); } }