SpringBoot集成Memcached

news/2024/7/5 2:06:12

SpringBoot集成Memcached

1、Memcached 介绍

Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中

缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储

键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过

memcached协议与守护进程通信。

因为 Spring Boot 没有针对 Memcached 提供对应的组建包,因此需要我们自己来集成。官方推出的 Java 客户端

Spymemcached 是一个比较好的选择之一。

Spymemcached 最早由 Dustin Sallings 开发,Dustin 后来和别人一起创办了 Couchbase (原NorthScale),职位

为首席架构师。2014 加入 Google。Spymemcached 是一个采用 Java 开发的异步、单线程的 Memcached 客户

端, 使用 NIO 实现。Spymemcached 是 Memcached 的一个流行的 Java client 库,性能表现出色,广泛应用于

Java + Memcached 项目中。

2、Windows下安装Memcached

官网上并未提供 Memcached 的 Windows 平台安装包,我们可以使用以下链接来下载,你需要根据自己的系统平

台及需要的版本号点击对应的链接下载即可:

  • 32位系统 1.2.5版本:http://static.runoob.com/download/memcached-1.2.5-win32-bin.zip

  • 32位系统 1.2.6版本:http://static.runoob.com/download/memcached-1.2.6-win32-bin.zip

  • 32位系统 1.4.4版本:http://static.runoob.com/download/memcached-win32-1.4.4-14.zip

  • 64位系统 1.4.4版本:http://static.runoob.com/download/memcached-win64-1.4.4-14.zip

  • 32位系统 1.4.5版本:http://static.runoob.com/download/memcached-1.4.5-x86.zip

  • 64位系统 1.4.5版本:http://static.runoob.com/download/memcached-1.4.5-amd64.zip

在 1.4.5 版本以前 memcached 可以作为一个服务安装,而在 1.4.5 及之后的版本删除了该功能。因此我们以下介

绍两个不同版本 1.4.4 及 1.4.5的不同安装方法。

2.1 memcached <1.4.5 版本安装

1、解压下载的安装包到指定目录。

2、在 1.4.5 版本以前 memcached 可以作为一个服务安装,使用管理员权限运行以下命令:

c:\memcached\memcached.exe -d install

3、然后我们可以使用以下命令来启动和关闭 memcached 服务:

c:\memcached\memcached.exe -d start
c:\memcached\memcached.exe -d stop

4、如果要修改 memcached 的配置项, 可以在命令行中执行 regedit.exe 命令打开注册表并找到

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached 来进行修改。

如果要提供 memcached 使用的缓存配置可以修改 ImagePath 为:

"c:\memcached\memcached.exe" -d runservice -m 512

-m 512 意思是设置 memcached 最大的缓存配置为512M。

此外我们还可以通过使用 memcached.exe -h 命令查看更多的参数配置。

5、如果我们需要卸载 memcached ,可以使用以下命令:

c:\memcached\memcached.exe -d uninstall

2.2 memcached >= 1.4.5 版本安装

1、解压下载的安装包到指定目录。

2、在 memcached1.4.5 版本之后,memcached 不能作为服务来运行,需要使用任务计划中来开启一个普通的

进程,在 window 启动时设置 memcached自动执行。

我们使用管理员身份执行以下命令将 memcached 添加来任务计划表中:

schtasks /create /sc onstart /tn memcached /tr "'c:\memcached\memcached.exe' -m 512"

注意:-m 512 意思是设置 memcached 最大的缓存配置为512M。

注意:我们可以通过使用 c:\memcached\memcached.exe -h 命令查看更多的参数配置。

3、如果需要删除 memcached 的任务计划可以执行以下命令:

schtasks /delete /tn memcached

3、整合Memcached

3.1 pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>spring-boot-memcache-spymemcached</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-memcache-spymemcached</name>
    <description>spring-boot-memcache-spymemcached</description>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.2 配置文件

memcache.ip=127.0.0.1
memcache.port=11211

分别配置 memcache 的 Ip 地址和 端口。

3.3 设置配置对象

创建 MemcacheSource 接收配置信息

package com.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "memcache")
public class MemcacheSource {

    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;
    }
}

@ConfigurationProperties(prefix = "memcache") 的意思会以 memcache.* 为开通将对应的配置文件加载

到属性中。

3.4 启动初始化 MemcachedClient

利用 CommandLineRunner 在项目启动的时候配置好 MemcachedClient

package com.example.config;

import net.spy.memcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetSocketAddress;

@Component
public class MemcachedRunner implements CommandLineRunner {

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

    @Resource
    private MemcacheSource memcacheSource;

    private MemcachedClient client = null;

    @Override
    public void run(String... args) throws Exception {
        try {
            client = new MemcachedClient(new InetSocketAddress(memcacheSource.getIp(), memcacheSource.getPort()));
        } catch (IOException e) {
            logger.error("inint MemcachedClient failed ", e);
        }
    }

    public MemcachedClient getClient() {
        return client;
    }

}

3.5 启动类

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

	public static void main(String[] args) {

		SpringApplication.run(Application.class, args);
	}

}

3.6 测试

package com.example;

import com.example.config.MemcachedRunner;
import net.spy.memcached.MemcachedClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RepositoryTests {

    @Resource
    private MemcachedRunner memcachedRunner;

    @Test
    public void testSetGet() {
        MemcachedClient memcachedClient = memcachedRunner.getClient();
        memcachedClient.set("testkey", 1000, "666666");
        System.out.println("***********  " + memcachedClient.get("testkey").toString());
    }

}

使用中先测试插入一个 key 为 testkey ,1000 为过期时间单位为 毫秒,最后的 666666 为 key 对应的值。

执行测试用例 testSetGet ,控制台输出内容:

***********  666666

表明测试成功。


http://lihuaxi.xjx100.cn/news/1960571.html

相关文章

【DP】583.两个字符串的删除操作

题目 法1&#xff1a;DP 本质是不带替换操作的最小编辑距离问题&#xff01;&#xff01;&#xff01; class Solution {public int minDistance(String word1, String word2) {int m word1.length() 1, n word2.length() 1;int[][] dp new int[m][n];for (int i 1; i…

基于EEMD-SpEn(样本熵)联合小波阈值去噪

代码原理 以样本熵为阈值的EEMD联合小波阈值去噪方法是一种结合了经验模态分解&#xff08;EEMD&#xff09;、样本熵和小波阈值去噪的信号处理方法&#xff0c;用于去除信号中的噪声。 下面是具体的步骤&#xff1a; 1. 经验模态分解&#xff08;EEMD&#xff09;&#xff…

又涨了:net的域名铁定涨价

关注卢松松&#xff0c;会经常给你分享一些我的经验和观点。 又要涨价了&#xff0c;又要涨价了&#xff0c;又要涨价了!继.com域名涨价后&#xff0c;.net的域名也逐步涨价。最近一年来域名疯狂涨价&#xff0c;几个月内已经几乎翻番。 阿里云2月1日起上调.net英文域名价格…

vue项目之.env文件.env.dev、test、pro

.env文件是vue运行项目时的环境配置文件。 .env: 全局默认配置文件&#xff0c;所有环境(开发、测试、生产等&#xff09;均会加载并合并该文件 .env.development(开发环境默认命名) 开发环境的配置&#xff0c;文件名默认为.env.development,如果需要改名也是可以的&#xf…

白嫖aws创建Joplin server服务器

网上有很多的Joplin服务器的搭建教程&#xff0c;但是基本都是抄来抄去&#xff0c;对初学者实在是太不友好了。 话不多说&#xff0c;说干就干&#xff0c;自己从头找资料搭了一个&#xff0c;这可能是全网最好的Joplin服务器搭建教程了。 aws服务器 aws的服务器还是很香的&…

pyDAL一个python的ORM(9) pyDAL的嵌套查询

假设有以下两个表&#xff1a; db.define_table(person,Field(id, string), Field(‘name, string), Field(‘dept, string)) db.define_table(things,Field(id, string), Field(‘name, string), Field(‘owner, string)) 一、使用belongs进行嵌套查询 我们查询要求&#…

04.neuvector进程策略生成与管控实现

原文链接&#xff0c;欢迎大家关注我的github 一、进程学习管控的实现方式 策略学习实现&#xff1a; 进程的学习与告警主要依据通过netlink socket实时获取进程启动和退出的事件: 1.创建netLink socket&#xff1b; 2.通过创建netlink的fd对进程的事件进行捕获与更新&#x…

crackmapexec工具详解

下载地址&#xff1a;https://github.com/Porchetta-Industries/CrackMapExec wiki&#xff1a;https://www.crackmapexec.wiki/ 1.安装&#xff08;MAC&#xff09; 1.1.python3.9 pipx 安装&#xff08;运行软件有警告&#xff0c;推荐 python3.11 pipx 安装&#xff09; …