本文主要实现spring boot集成SpyMemcached这种方式(停止更新),不推荐
第一步:windows下安装Memcached
在网上查了大量的参考资料,发现有很多种实现方式,我们在第一种,首先在https://www.runoob.com/memcached/window-install-memcached.html里面下载相应的版本,我一开始现在的是64位的1.4.5版本,然后按照教程里面的安装手册安装,我发现并没有安装成功,查询了大量的资料,找了各种原因(telnet 127.0.0.1 11211测试等等),都没有找到相应的解决办法,所以我就放弃了1.4.5版本,转而安装1.4.4版本,可以发布成server的版本。
具体如何安装以及修改参数都在上面的网页教程里面有相应的记录,这里我需要说明的是:当执行c:\memcached\memcached.exe -d start之后,这个memcached进行就会启动,关机重启电脑也会自动启动这个进程。不用再刻意的去配置开机启动。
首先确保这个服务开启了,才能在后续代码里面使用memcached服务。
![](https://img8.php1.cn/3cdc5/1284f/b64/f7507a5dc2da977c.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hoZjg1Mjk2Mw==,size_16,color_FFFFFF,t_70)
第二步:在代码中添加maven依赖
net.spyspymemcached2.12.2
第三步:在application.properties中配置memcache相关配置信息
memcache.ip=127.0.0.1
memcache.port=11211
第四步:编写SpyMemcacheConfig配置类
@Configuration
public class SpyMemcacheConfig implements CommandLineRunner{@Value("${memcache.ip}")private String ip;@Value("${memcache.port}")private int port;private MemcachedClient client = null;@Overridepublic void run(String... args) throws Exception {try {client = new MemcachedClient(new InetSocketAddress(ip,port));} catch (IOException e) {}}public MemcachedClient getClient() {return client;}
}
第五步:编写测试spyMemcache的controller类
@RestController
public class SpyMemcacheController {@Autowiredprivate SpyMemcacheConfig spyMemcacheConfig;@RequestMapping("/spyMemcacheIndex")public String spyMemcacheIndex() throws InterruptedException {/*这个过期时间单位是秒,最大值是60*60*24*30*/spyMemcacheConfig.getClient().set("spyMemcachedKey",1,"张三");System.out.println("基于spyMemcached实现,现在的值为 "+spyMemcacheConfig.getClient().get("spyMemcachedKey"));Thread.sleep(2000);System.out.println("1秒后缓存内容清除,现在的值为: "+spyMemcacheConfig.getClient().get("spyMemcachedKey"));return "aaaaa";}
}
第六步:测试
启动程序,输入http://localhost:8080/spyMemcacheIndex,输出结果如图所示:
![](https://img8.php1.cn/3cdc5/1284f/b64/c0c82c7d6a42b188.png)