当前位置: 首页 > news >正文

Spring Boot 整合分布式缓存 Memcached

Memcached是一个开源、高性能,将数据分布于内存中并使用key-value存储结构的缓存系统。它通过在内存中缓存数据来减少向数据库的频繁访问连接的次数,可以提高动态、数据库驱动之类网站的运行速度。

Memcached在使用是比较简单的,在操作上基本就类似于操作字典结构的对象一样

1 添加依赖

这里需要添加上web、swagger和spymemcached的依赖,Swagger是为了方便接口测试。

对于spymemcached的支持,其实只要如下这个依赖包就可以了。

<!-- https://mvnrepository.com/artifact/net.spy/spymemcached -->
<dependency><groupId>net.spy</groupId><artifactId>spymemcached</artifactId><version>2.12.3</version>
</dependency>

2 添加相关配置

2.1 添加swagger 配置

添加一个swagger 配置类,在工程下新建 config 包并添加一个 SwaggerConfig 配置类,除了常规配置外,加了一个令牌属性,可以在接口调用的时候传递令牌。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket createRestApi(){return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();}private ApiInfo apiInfo(){return new ApiInfoBuilder().title("Swagger API Doc").description("This is a restful api document of Swagger.").version("1.0").build();}}
2.2.在配置文件添加memcache的主机端口信息

application.properties

memcache.ip=127.0.0.1
memcache.port=11211

application.yml

memcache:ip: 127.0.0.1port: 11211
2.3.添加一个MemcacheConfig配置类,读取主机端口并构造一个MemcachedClient。

MemcacheConfig.java

import java.io.IOException;
import java.net.InetSocketAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import net.spy.memcached.MemcachedClient;@Configuration
public class MemcacheConfig {@Value("${memcache.ip}")private String ip;@Value("${memcache.port}")private int port;@Beanpublic MemcachedClient getClient() {MemcachedClient memcachedClient = null;try {memcachedClient  = new MemcachedClient(new InetSocketAddress(ip, port));} catch (IOException e) {e.printStackTrace();}return memcachedClient;}
}
2.4 编写业务接口

编写一个业务控制器,通过MemcachedClient实现对缓存的设置和读取。

MemcacheController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;@RestController
public class MemcacheController {private Logger logger = LoggerFactory.getLogger(getClass());@Autowiredprivate MemcachedClient memcachedClient;@GetMapping("/info")public String memcacheGetValue() throws InterruptedException {// 取出缓存Object value = memcachedClient.get("userName");logger.info("取出缓存 "+value);return "取出的值  "+value;}@GetMapping("/save")public String saveValue(@RequestParam String userName) throws InterruptedException {// 放入缓存, 过期时间为5000,单位为毫秒OperationFuture<Boolean> flag = memcachedClient.set("userName", 5000, userName);return "保存成功";}
}

3 编译运行测试

3.1. 右键项目 -> Run as -> Maven install,开始执行Maven构建,第一次会下载Maven依赖,可能需要点时间

在这里插入图片描述

3.2. 右键文件 DemoApplication.java -> Run as -> Java Application,开始启动应用

在这里插入图片描述

3.3. 打开浏览器,访问:http://localhost:8899/swagger-ui.html,进入swagger接口文档界面。

这里的端口根据具体的项目启动来查看,我这里是 8899
在这里插入图片描述

http://www.lryc.cn/news/27485.html

相关文章:

  • 嵌入式学习笔记——STM32单片机开发前的准备
  • 客户案例|FPGA研发管理解决方案:UniPro瀑布+敏捷 打造高效能组织
  • 【信息学奥赛】1400:统计单词数
  • # 技术详解: 利用CI同步文章以及多端发布
  • 分形维数的计算方法汇总
  • 微积分小课堂:积分(从微观趋势了解宏观变化)
  • 4道数学题,求解极狐GitLab CI 流水线|第4题:合并列车
  • 代码规范简述
  • 【Java集合框架】篇五:Map接口
  • Typroa安装教程
  • 【MySQL】存储引擎
  • 芯驰(E3-gateway)开发板环境搭建以及调试遇到问题的解决
  • 【大数据监控】Prometheus、Node_exporter、Graphite_exporter安装部署详细文档
  • 《C++ Primer》 第十一章 关联容器
  • WebRTC标准与框架解读(1)
  • 数据结构的一些基础概念
  • 【Python每日一练】总目录(不断更新中...)
  • latex插入图片(自用)
  • 【微信小程序】-- 网络数据请求(十九)
  • K8S 实用工具之一 - 如何合并多个 kubeconfig?
  • 阿里云ECS服务器的6大功能组件
  • 外贸建站多少钱?不同预算对应的建站方案!
  • Vue3中hook的使用及使用中遇到的坑
  • 数据库-差集交集并集
  • spark性能调优(四):网络
  • 高性能 WPF 图表控件LightningChart.NET:支持从 Web 服务器获取数据 | 附最新版试用下载
  • 文科女生月入14k背后:转行IT软件测试不是谁都学得来!
  • GB28181监控视频统一汇聚平台LiveGBS将海康大华华为宇视等厂家监控设备统一接入后如何生成固定播放链接或者固定的流地址可以直接无插件播放或者拉取
  • 认识BUG
  • C++string类型内置的搜索函数