springboot 引入memcached
0、安装memcache
启动memcache
1、pom.xml 引入依赖
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.2</version>
</dependency>
MemcachedController:
package com.example.springbootlearn.controller;
import com.example.springbootlearn.runner.MemcachedRunner;
import net.spy.memcached.MemcachedClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class MemcachedController {
@Resource
private MemcachedRunner memcachedRunner;
@RequestMapping("/hellomemcache")
@ResponseBody
public String memcache() {
MemcachedClient memcachedClient = memcachedRunner.getMemcachedClient();
memcachedClient.set("hello",1000,"memcached!");
return (String) memcachedClient.get("hello");
}
}
MemcacheConfiguration:
package com.example.springbootlearn.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "memcache")
public class MemcacheConfiguration {
private String ip;
private int port;
}
MemcachedRunner:
实现CommandLineRunner接口,在项目启动的时候配置 MemcachedClient
package com.example.springbootlearn.runner;
import com.example.springbootlearn.config.MemcacheConfiguration;
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.net.InetSocketAddress;
@Component
public class MemcachedRunner implements CommandLineRunner {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
private MemcacheConfiguration memcacheConfiguration;
private MemcachedClient memcachedClient = null;
@Override
public void run(String... args) throws Exception {
try {
memcachedClient = new MemcachedClient(new InetSocketAddress(memcacheConfiguration.getIp(), memcacheConfiguration.getPort()));
} catch (Exception ex) {
logger.error("初始化MemcachedClient失败 ",ex);
}
}
public MemcachedClient getMemcachedClient() {
return memcachedClient;
}
}
application.properties:
memcache配置项
memcache.ip=127.0.0.1
memcache.port=11211
启动项目,访问接口