安装Memcached
下载地址
32位系统 1.2.5版本:http://static.jyshare.com/download/memcached-1.2.5-win32-bin.zip
32位系统 1.2.6版本:http://static.jyshare.com/download/memcached-1.2.6-win32-bin.zip
32位系统 1.4.4版本:http://static.jyshare.com/download/memcached-win32-1.4.4-14.zip
64位系统 1.4.4版本:http://static.jyshare.com/download/memcached-win64-1.4.4-14.zip
32位系统 1.4.5版本:http://static.jyshare.com/download/memcached-1.4.5-x86.zip
64位系统 1.4.5版本:http://static.jyshare.com/download/memcached-1.4.5-amd64.zip
解压,点击memcached.exe
参考文章
https://www.runoob.com/memcached/window-install-memcached.html
集成sprnigboot
pom
<!-- https://mvnrepository.com/artifact/net.spy/spymemcached -->
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version>
</dependency>
application.properties
memcache.ip=127.0.0.1
memcache.port=11211
添加一个MemcacheConfig配置类读取主机端口并构造一个MemcachedClient。
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;
@Bean
public MemcachedClient getClient() {
MemcachedClient memcachedClient = null;
try {
memcachedClient = new MemcachedClient(new InetSocketAddress(ip, port));
} catch (IOException e) {
e.printStackTrace();
}
return memcachedClient;
}
}
编写一个业务控制器,通过MemcachedClient实现对缓存的设置和读取。
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());
@Autowired
private 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 "保存成功";
}
}
参考文章
https://zhuanlan.zhihu.com/p/611172374