前言

Memcached 是一个高性能的分布式内存对象缓存系统,其存储性能在某些方面不比redis差,甚至在文本类型数据的存储上性能略优于redis,本文将介绍如何在springboot中集成memcached

准备工作

首先我们需要一款客户端连接对象,类似于我们在使用redis时使用的jedis , 目前memcached主流的客户端是Xmemcached,如果使用的是maven构建项目,则引入对应的依赖

   <!--引入memcached-->
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>2.4.5</version>
</dependency>

配置

memcached在yml(properties)文件的相关配置

# memcached配置
memcached:
server: 1.1.1.1:3333 2.2.2.2:4444 #memcached服务器集群(格式为host:port,多个服务器之间用空格隔开)
opTimeout: 3000 #接口操作的默认超时时间,可以被接口覆盖
poolSize: 10 #池子大小
failureMode: false #是否开启失败模式,默认为false
enabled: true # 是否使用memcached缓存

将memcached的配置由bean来管理,方便我们调用

 package com.me.config.properties;

 import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; /**
* @author : wang zns
* @date : 2018-12-19
*/
@Component
@ConfigurationProperties(prefix = "memcached")
public class MemcachedProperties { /**
* 服务器
*/
private String server; /**
* 操作超时时间,可以被API覆盖
*/
private Integer opTimeout;
/**
* 连接池大小
*/
private Integer poolSize; /**
* 是否开启失败模式
*/
private boolean failureMode; /**
* 是否使用memcached缓存
*/
private boolean enabled; public String getServer() {
return server;
} public void setServer(String server) {
this.server = server;
} public Integer getOpTimeout() {
return opTimeout;
} public void setOpTimeout(Integer opTimeout) {
this.opTimeout = opTimeout;
} public Integer getPoolSize() {
return poolSize;
} public void setPoolSize(Integer poolSize) {
this.poolSize = poolSize;
} public boolean isFailureMode() {
return failureMode;
} public void setFailureMode(boolean failureMode) {
this.failureMode = failureMode;
} public boolean isEnabled() {
return enabled;
} public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}

memcached配置类(创建memcached客户端对象,并注入spring容器中)

 package com.me.config;

 import cn.stylefeng.guns.config.properties.MemcachedProperties;
import lombok.extern.slf4j.Slf4j;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; /**
* @author : wang zns
* @date : 2018-12-19
*/
@Configuration
@Slf4j
public class MemcachedConfig { @Autowired
private MemcachedProperties memcachedProperties; @Bean(name = "memcachedClientBuilder")
public MemcachedClientBuilder getBuilder() {
MemcachedClientBuilder memcachedClientBuilder = new XMemcachedClientBuilder(memcachedProperties.getServer()); // 内部采用一致性哈希算法
memcachedClientBuilder.setSessionLocator(new KetamaMemcachedSessionLocator());
// 操作的超时时间
memcachedClientBuilder.setOpTimeout(memcachedProperties.getOpTimeout());
// 采用二进制传输协议(默认为文本协议)
memcachedClientBuilder.setCommandFactory(new BinaryCommandFactory());
// 设置连接池的大小
memcachedClientBuilder.setConnectionPoolSize(memcachedProperties.getPoolSize());
// 是否开起失败模式
memcachedClientBuilder.setFailureMode(memcachedProperties.isFailureMode());
return memcachedClientBuilder;
} /**
* 由Builder创建memcachedClient对象,并注入spring容器中
* @param memcachedClientBuilder
* @return
*/
@Bean(name = "memcachedClient")
public MemcachedClient getClient(@Qualifier("memcachedClientBuilder") MemcachedClientBuilder memcachedClientBuilder) {
MemcachedClient client = null;
try {
client = memcachedClientBuilder.build();
} catch(Exception e) {
log.info("exception happens when bulid memcached client{}",e.toString());
}
return client;
} }

使用

有了client对象之后,我们可以像直接操作服务端那样进行对应的操作,下面用一个小案例进行演示

service

 package cn.stylefeng.guns.modular.housemanage.cache;

 import cn.stylefeng.guns.modular.system.model.TblHouse;

 /**
* 房屋管理缓存 业务层
* @author : wang zns
* @date : 2018-12-19
*/
public interface HouseManageCacheService { /**
* 添加
* @param tblHouse
*/
void add(TblHouse tblHouse); /**
* 根据主键删除
* @param tblHouseId
*/
void delete(Integer tblHouseId); }

serviceImpl

 package cn.stylefeng.guns.modular.housemanage.cache;

 import cn.stylefeng.guns.modular.housemanage.service.ITblHouseService;
import cn.stylefeng.guns.modular.system.model.TblHouse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.rubyeye.xmemcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* @author : wang zns
* @date : 2018-12-19
*/
@Service
@Slf4j
public class HouseManageCacheServiceImpl implements HouseManageCacheService{ @Autowired
private MemcachedClient memcachedClient;
@Autowired
private ITblHouseService iTblHouseService; @Override
public void add(TblHouse tblHouse) {
// 先入库,入库成功则入缓存
boolean isSuccess = iTblHouseService.insert(tblHouse);
if (isSuccess) {
try {
String houseJsonStr = JSON.toJSONString(tblHouse);
memcachedClient.set(String.valueOf(tblHouse.getId()),0,houseJsonStr);
} catch (Exception e) {
log.info("exception happens when add House:{}",e.toString());
throw new RuntimeException(e.getMessage());
}
}
} @Override
public void delete(Integer tblHouseId) {
// 先删除数据库内容,成功则清空缓存
boolean isSuccess = iTblHouseService.deleteById(tblHouseId);
if (isSuccess) {
try {
memcachedClient.delete(String.valueOf(tblHouseId));
} catch (Exception e) {
log.info("exception happens when delete House:{}",e.toString());
throw new RuntimeException(e.getMessage());
}
}
} }

controller

  /**
* 新增房屋管理
*/
@RequestMapping(value = "/add")
@ResponseBody
public Object add(@Valid TblHouse tblHouse, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
// 如果确定要使用缓存
if (memcachedProperties.isEnabled()) {
houseManageCacheService.add(tblHouse);
} else {
tblHouseService.insert(tblHouse);
}
return SUCCESS_TIP;
} /**
* 删除房屋管理
*/
@RequestMapping(value = "/delete")
@ResponseBody
public Object delete(@RequestParam Integer tblHouseId) {
if (memcachedProperties.isEnabled()) {
houseManageCacheService.delete(tblHouseId);
} else {
tblHouseService.deleteById(tblHouseId);
}
return SUCCESS_TIP;
}

运行结果:

springboot中集成memcached-LMLPHP

提交之后,去缓存服务器上查看

springboot中集成memcached-LMLPHP

至此,springboot中集成memcached就完成了

写在最后

springboot集成memcached非常简单,核心步骤就是添加依赖、创建client对象并注入spring容器、然后就是用client对象进行各种操作。

client的接口当然有非常多,xmemcached对接口进行了封装。

最后附上xmemcached官网的地址,里面的文档很详细  https://github.com/killme2008/xmemcached/wiki

05-17 08:44