SpringBoot整合Memached

一、Memached介绍

  Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。
  为了提高性能,memcached中保存的数据都存储在memcached内置的内存存储空间中。由于数据仅存在于内存中,因此重启memcached、重启操作系统会导致全部数据消失。另外,内容容量达到指定值之后,就基于LRU(Least Recently Used)算法自动删除不使用的缓存。memcached本身是为缓存而设计的服务器,因此并没有过多考虑数据的永久性问题。

二、安装步骤

windows安装

参考教材https://www.runoob.com/memcached/window-install-memcached.html

linux(Ubuntu/Debian)安装

  1. 要先安装libevent库
    sudo apt-get install libevent ibevent-dev

  2. 自动安装
    sudo apt-get install memcached

  3. 或者源代码的方式安装

从其官方网站(http://memcached.org)下载memcached
解压源码 tar -zxvf memcached-1.x.x.tar.gz
进入目录
配置 ./configure --prefix=/path/to/memcached
编译 make && make test
安装 sudo make install

更多参考https://www.runoob.com/memcached/memcached-install.html

安装完成后memcached已经启动了,我们先杀掉进程然后按照自己的方式作为后台服务启动。
/usr/bin/memcached -p 11211 -m 64m -d -u root
最后打开cmd,输入 telnet ip 11211来连接memcached进行测试。
注意: 我的自动安装后是在/usr/bin目录,实际情况要根据进程信息显示的目录为准。

  1. set foo 0 0 3 
  2. bar 
  3. STORED 
  4. get foo 
  5. VALUE foo 0 3 
  6. bar 
  7. END 
  8. quit 

三、完成整合

  1. 创建springboot项目memcached-demo
  2. 在 pomx 包中添加 spymemcached 的引用,Spymemcached 是一个采用 Java 开发的异步、单线程的 Memcached 客户端, 使用 NIO 实现。
  1. <dependency> 
  2. <groupId>net.spy</groupId> 
  3. <artifactId>spymemcached</artifactId> 
  4. <version>2.12.2</version> 
  5. </dependency> 
  1. 在application.properties文件填写配置信息
    memcached.ip=XXX
    memcached.port=11211
  2. 对应的配置读取类MemcachedConfig
@Component
@ConfigurationProperties(prefix = "memcached")
public class MemcachedConfig {

    private String ip;

    private int port;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}

  1. 项目启动时创建MemcachedClient实例
@SpringBootApplication
public class MemcachedDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MemcachedDemoApplication.class, args);
    }

    final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MemcachedConfig memcachedConfig;

    @Bean(name = "memcachedClient")
    public MemcachedClient getMemcachedClient(){
        try {
            MemcachedClient client = new MemcachedClient(new InetSocketAddress(memcachedConfig.getIp(), memcachedConfig.getPort()));
            return client;
        } catch (IOException e) {
            logger.error("初始化MemcachedClient失败,{}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
  1. 编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MemcachedDemoApplicationTests {

    @Autowired
    private MemcachedClient client;


    @Test
    public void contextLoads() {
        client.set("testKey",1000,"testValue");
        System.out.println("============testKey的值为:"+client.get("testKey"));
    }

}

四、测试总结

运行测试类MemcachedDemoApplicationTests中的contextLoads方法,控制台输出如下:

2019-05-06 19:52:26.693 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=/198.13.40.234:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2019-05-06 19:52:27.312  INFO 10348 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-05-06 19:52:27.668  INFO 10348 --- [           main] cn.sp.MemcachedDemoApplicationTests      : Started MemcachedDemoApplicationTests in 2.966 seconds (JVM running for 4.14)
============testKey的值为:testValue
2019-05-06 19:52:28.052  INFO 10348 --- [       Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2019-05-06 19:52:28.059 INFO net.spy.memcached.MemcachedConnection:  Shut down memcached client

Memcached上手起来还是比较简单,但是还有些其他命令需要熟悉,以及多台Memcached 的使用问题。
代码地址,点击这里

原文地址:https://www.cnblogs.com/2YSP/p/10821789.html