ubuntu安装并使用Memcached

1、选择较新的版本安装

访问官网:memcached - a distributed memory object caching system

我使用的是Memcached 1.6.22这个版本ReleaseNotes1622 · memcached/memcached Wiki · GitHub

下载地址:http://www.memcached.org/files/memcached-1.6.22.tar.gz

下载后,解压,然后到目录下执行安装命令:

./configure --prefix=/home/lighthouse/memcached && make && make test && sudo make install

发现这种安装方式无厘头,搞不懂安装到哪去了,无法执行./memcached命令,那换一种方式吧。

  1. 更新包管理器的索引:

sudo apt-update

  1. 安装Memcached:

sudo apt-get install memcached

  1. 验证Memcached版本:

memcached -h | grep 'memcached'

  1. 启动Memcached服务:

sudo service memcached start

  1. 设置Memcached在启动时自动运行:

sudo systemctl enable memcached

  1. 使用Memcached。你可以使用memcached客户端来与Memcached服务交互。例如,使用telnet连接到Memcached服务:

telnet localhost 11211

在telnet会话中,你可以使用Memcached命令存储和检索数据。例如:

set key1 0 60 5

value

STORED

get key1

VALUE key1 0 5

value

END

参数说明,参考:memcache使用手册 - 简书

可以使用如下命令查看memcached安装在哪里

whereis memcached

2、在java中使用memcached

2.1引入jar包

<dependency>
            <groupId>com.googlecode.xmemcached</groupId>
            <artifactId>xmemcached</artifactId>
            <version>2.4.7</version>
        </dependency>

2.2写个测试接口

package com.hmblogs.backend.controller;

import lombok.extern.slf4j.Slf4j;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.utils.AddrUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;

@RestController
@RequestMapping("/memcached")
@Slf4j
public class MemcachedController {

    @GetMapping("/test")
    public String hello() {
        MemcachedClient memcachedClient = null;
        try {
            MemcachedClientBuilder builder = new XMemcachedClientBuilder(
                    AddrUtil.getAddresses("43.138.0.199:11211")
            );
            log.info("aaaa");
            memcachedClient = builder.build();
            log.info("bbbb");
            // 存储数据
            memcachedClient.set("key1", 0, "value1");
            log.info("cccc");
            // 检索数据
            String value1 = memcachedClient.get("key1");
            log.info("dddd");
            return "key1: " + value1;

        } catch (Exception e) {
            log.info("error:{}",e);
        } finally {
            log.info("eeeee");
            if (memcachedClient != null) {
                try {
                    memcachedClient.shutdown();
                } catch (IOException e) {
                    log.info("shutdown error:{}",e);
                }
            }
        }
        return "ok";
    }
}

2.3验证该接口

2024-04-10 17:42:37.446 [http-nio-8081-exec-1] INFO  [com.hmblogs.backend.controller.MemcachedController] - aaaa
2024-04-10 17:42:37.462 [http-nio-8081-exec-1] INFO  [net.rubyeye.xmemcached.XMemcachedClient] - XMemcachedClient is using Text protocol
2024-04-10 17:42:37.504 [http-nio-8081-exec-1] INFO  [com.google.code.yanf4j.nio.impl.SelectorManager] - Creating 2 reactors...
2024-04-10 17:42:37.511 [http-nio-8081-exec-1] INFO  [c.google.code.yanf4j.core.impl.AbstractController] - The Controller started at localhost/127.0.0.1:0 ...
2024-04-10 17:42:37.525 [http-nio-8081-exec-1] INFO  [com.hmblogs.backend.controller.MemcachedController] - bbbb
2024-04-10 17:42:37.529 [http-nio-8081-exec-1] INFO  [com.hmblogs.backend.controller.MemcachedController] - error:{}
net.rubyeye.xmemcached.exception.MemcachedException: There is no available connection at this moment
        at net.rubyeye.xmemcached.impl.MemcachedConnector.send(MemcachedConnector.java:493)
        at net.rubyeye.xmemcached.XMemcachedClient.sendCommand(XMemcachedClient.java:325)
        at net.rubyeye.xmemcached.XMemcachedClient.sendStoreCommand(XMemcachedClient.java:2380)
        at net.rubyeye.xmemcached.XMemcachedClient.set(XMemcachedClient.java:1285)
        at net.rubyeye.xmemcached.XMemcachedClient.set(XMemcachedClient.java:1339)
        at net.rubyeye.xmemcached.XMemcachedClient.set(XMemcachedClient.java:1328)
        at com.hmblogs.backend.controller.MemcachedController.hello(MemcachedController.java:29)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:829)
2024-04-10 17:42:37.529 [http-nio-8081-exec-1] INFO  [com.hmblogs.backend.controller.MemcachedController] - eeeee
2024-04-10 17:42:37.530 [http-nio-8081-exec-1] INFO  [c.google.code.yanf4j.core.impl.AbstractController] - Controller has been stopped.

然后把代码改成如下:

package com.hmblogs.backend.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import static junit.framework.Assert.*;
import java.util.concurrent.TimeoutException;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;


@RestController
@RequestMapping("/memcached")
@Slf4j
public class MemcachedController {

    @GetMapping("/test")
    public void hello() {
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(
                AddrUtil.getAddresses("43.138.0.199:11211"),
                new int[]{1, 1, 1, 1});
        log.info("aaaa");
        // 设置连接池大小,即客户端个数
        builder.setConnectionPoolSize(50);

        // 宕机报警
        builder.setFailureMode(true);

        // 使用二进制文件
        builder.setCommandFactory(new BinaryCommandFactory());
        log.info("bbbb");
        MemcachedClient memcachedClient = null;
        try {
            memcachedClient = builder.build();
            log.info("cccc");
            try {
                // 设置/获取
                memcachedClient.set("zlex", 36000, "set/get");
                log.info("zlex:" + memcachedClient.get("zlex"));
                assertEquals("set/get", memcachedClient.get("zlex"));

                // 替换
                memcachedClient.replace("zlex", 36000, "replace");
                assertEquals("replace", memcachedClient.get("zlex"));

                // 移除
                memcachedClient.delete("zlex");
                assertNull(memcachedClient.get("zlex"));
                log.info("dddd");
            } catch (TimeoutException e) {
                // TODO Auto-generated catch block
                log.error("TimeoutException:{}", e);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                log.error("InterruptedException:{}", e);
            } catch (MemcachedException e) {
                // TODO Auto-generated catch block
                log.error("MemcachedException:{}", e);
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error("error:{}", e);
        } finally {
            log.info("eeee");
            if (memcachedClient != null) {
                try {
                    memcachedClient.shutdown();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    log.error("shutdown error:{}", e);
                }
            }
        }
    }
}


再次调用该接口,报如下信息:没有打印zlex,也没有打印dddd

然后发现这里讲的挺好的,java操作memcached:Java 连接 Memcached 服务 | 菜鸟教程

但是要这样引入本地包,不适合maven项目,打包会打不进去你业务系统的jar文件。

后面尝试在pom.xml文件里面加入依赖,发现有问题,后面在Central Repository:

这里仔细一看,artifactId少了最前面的"spy"三个字母。

添加依赖如下:

<dependency>
            <groupId>net.spy</groupId>
            <artifactId>spymemcached</artifactId>
            <version>2.10.3</version>
        </dependency>

然后使用如下代码发ubuntu环境验证:

package com.hmblogs.backend.controller;

import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.MemcachedClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;


@RestController
@RequestMapping("/memcached")
@Slf4j
public class MemcachedController {

    @GetMapping("/test")
    public void hello() {
        try{
            // 连接本地的 Memcached 服务
            MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
            log.info("Connection to server successful.");

            // 存储数据
            Future fo = mcc.set("runoob", 900, "Free Education");

            // 查看存储状态
            log.info("set status:" + fo.get());

            // 输出值
            log.info("runoob value in cache - " + mcc.get("runoob"));

            // 关闭连接
            mcc.shutdown();

        }catch(Exception ex){
            log.info( "cuowule:"+ex.getMessage() );
        }
    }
}


发到环境后,调用该接口,日志文件中打印如下:

搞好了。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值