简介
Memcached 是一个高性能的分布式内存对象的key-value缓存系统,用于动态Web应用以减轻数据库负载,现在也有很多人将它作为内存式数据库在使用,memcached通过它的自定义协议与客户端交互,而XMemcached就是它的一个java客户端实现。
官网:->直达
添加依赖
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>2.4.7</version>
</dependency>
配置
属性配置
spring:
memcached:
# memcached服务器节点
servers: 127.0.0.1:11211
# nio连接池的数量
poolSize: 10
# 设置默认操作超时
opTimeout: 3000
# 是否启用url encode机制
sanitizeKeys: false
属性类设置
新建一个XMemcachedProperties
的配置类,该配置类用来映射读取application.yml文件中关于memcached的配置项。
@ConfigurationProperties(prefix = "spring.memcached")
@PropertySource("classpath:application.yml")
@Configuration
@Data
public class XMemcachedProperties {
/**
* memcached服务器节点
*/
private String servers;
/**
* nio 连接池的数量
*/
private Integer poolSize;
/**
* 设置默认操作超时
*/
private Long opTimeout;
/**
* 是否启用url encode 机制
*/
private Boolean sanitizeKeys;
}
配置类设置
新建一个配置类MemcachedConfig
,该配置类是为了将MemcachedClient注入到Spring容器,方便我们后续使用自动注入的方式使用MemcachedClient。如下:
@Configuration
public class MemcachedConfig {
@Autowired
private XMemcachedProperties xMemcachedProperties;
@Bean
public MemcachedClient memcachedClient(){
MemcachedClient memcachedClient = null;
try {
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(xMemcachedProperties.getServers()));
builder.setFailureMode(false);
builder.setSanitizeKeys(xMemcachedProperties.getSanitizeKeys());
builder.setConnectionPoolSize(xMemcachedProperties.getPoolSize());
builder.setOpTimeout(xMemcachedProperties.getOpTimeout());
builder.setSessionLocator(new KetamaMemcachedSessionLocator());
builder.setCommandFactory(new BinaryCommandFactory());
memcachedClient = builder.build();
} catch (IOException e) {
throw new RuntimeException(e);
}
return memcachedClient;
}
}
使用案例
添加缓存
@SpringBootTest
public class MemcachedTest {
@Autowired
private MemcachedClient memcachedClient;
@Test
void Test() throws InterruptedException, TimeoutException, MemcachedException {
// 设置缓存,永不过期
memcachedClient.set("a", 0, 1);
// 设置缓存,10秒过期
memcachedClient.set("b", 10, "Test123");
}
}
更新缓存过期时间
@SpringBootTest
public class MemcachedTest {
@Autowired
private MemcachedClient memcachedClient;
@Test
void touchTest() throws InterruptedException, TimeoutException, MemcachedException {
// 延缓缓存过期时间20秒
memcachedClient.touch("a", 20);
}
}
删除缓存
@SpringBootTest
public class MemcachedTest {
@Autowired
private MemcachedClient memcachedClient;
@Test
void deleteTest() throws InterruptedException, TimeoutException, MemcachedException {
memcachedClient.delete("a");
}
}
获取缓存
@SpringBootTest
public class MemcachedTest {
@Autowired
private MemcachedClient memcachedClient;
@Test
void getTest() throws InterruptedException, TimeoutException, MemcachedException {
String a = memcachedClient.get("a");
}
}
原创文章,作者:jiafegn,如若转载,请注明出处:https://www.techlearn.cn/archives/515