0、pom.xml依赖

<!-- LMDB --><dependency><groupId>org.lmdbjava</groupId><artifactId>lmdbjava</artifactId><version>0.7.0</version></dependency>

1、application.properties配置:

lmdb.path=E:\\lmdb
#单位为MB
lmdb.max.size=256
lmdb.database.count=10

2、LmdbServier 工具类


import lombok.extern.slf4j.Slf4j;
import org.lmdbjava.*;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Integer.BYTES;
import static java.nio.ByteBuffer.allocateDirect;
import static org.lmdbjava.ByteBufferProxy.PROXY_OPTIMAL;
import static org.lmdbjava.DbiFlags.MDB_CREATE;
import static org.lmdbjava.Env.create;/***  Lmdb操作工具类** @author jack<br>* @version 1.0<br>* @CreateDate 2020年5月11日 <br>*/
@Slf4j
@Service
public class LmdbService {/*** lmdb path*/@Value("${lmdb.path}")private String lmdbPath;/*** env*/private Env<ByteBuffer> env;/*** lmdb max size*/@Value("${lmdb.max.size}")private int lmdbMaxSize;/*** lmdb库的数量*/@Value("${lmdb.database.count}")private int lmdbDatabaseCount;/*** Description: 初始化操作 <br>* @author jack<br>* @version 1.0<br>* @CreateDate 2020年5月11日 <br>*/@PostConstructprivate void init(){try {final File path = new File(lmdbPath);env = create(PROXY_OPTIMAL).setMapSize(lmdbMaxSize * 1024 * 1024).setMaxDbs(lmdbDatabaseCount).setMaxReaders(lmdbDatabaseCount*2).open(path);log.info("初始化Lmdb成功......");} catch (Exception e) {throw new LmdbException("IO failure", e);}}/*** Description: 向库中插入数据 <br>* @param dbName dbname* @param key value 数据* @author jack<br>* @version 1.0<br>* @CreateDate 2020年5月11日 <br>*/public void putValueToDb(String dbName, String key,String value) {final Dbi<ByteBuffer> db = env.openDbi(dbName, MDB_CREATE);try (Txn<ByteBuffer> txn = env.txnWrite()) {final Cursor<ByteBuffer> c = db.openCursor(txn);c.put(bb(key), bb(value));c.close();txn.commit();}}/*** Description: 根据指定的key获取数据 <br>* @param dbName dbname* @param key key* @author jack<br>* @version 1.0<br>* @CreateDate 2020年5月11日 <br>*/public String getValueByKey(String dbName, String key) {final Dbi<ByteBuffer> db = env.openDbi(dbName, MDB_CREATE);final Cursor<ByteBuffer> c;String value ="";try (Txn<ByteBuffer> txn = env.txnRead()) {c = db.openCursor(txn);c.get(bb(key),GetOp.MDB_SET_KEY);ByteBuffer byteBuffer = c.val();c.close();value =  StandardCharsets.UTF_8.decode(byteBuffer).toString();}return value;}/*** Description: 获取库下所有的数据 <br>* @param dbName dbname* @author jack<br>* @version 1.0<br>* @CreateDate 2020年5月11日 <br>*/public Map<String, String> getAllValueByDbName(String dbName) {final Dbi<ByteBuffer> db = env.openDbi(dbName, MDB_CREATE);Map<String, String> map = new HashMap<>();try (Txn<ByteBuffer> txn = env.txnRead()) {Cursor<ByteBuffer> cursor = db.openCursor(txn);while (cursor.next()) {ByteBuffer key = cursor.key();ByteBuffer val = cursor.val();byte[] k = new byte[key.capacity()];byte[] v = new byte[val.capacity()];key.get(k);val.get(v);map.put(new String(k,StandardCharsets.UTF_8), new String(v,StandardCharsets.UTF_8));}cursor.close();}return map;}/*** Description: 根据dbname获取该库下的数量 <br>* @param dbName dbname* @author jack<br>* @version 1.0<br>* @CreateDate 2020年5月11日 <br>*/public long getDbCount(String dbName) {return getAllValueByDbName(dbName).size();}/*** 格式化 ByteBuffer* @param value* @author jack<br>* @version 1.0<br>* @CreateDate 2020年5月11日 <br>*/static ByteBuffer bb(final int value) {final ByteBuffer bb = allocateDirect(BYTES);bb.putInt(value).flip();return bb;}/*** 格式化 ByteBuffer* @param value* @author jack<br>* @version 1.0<br>* @CreateDate 2020年5月11日 <br>*/static ByteBuffer bb(final String value) {byte[] val = value.getBytes(StandardCharsets.UTF_8);final ByteBuffer bb = allocateDirect(val.length);bb.put(val).flip();return bb;}}

3、lmdb数据库名称枚举:LmdbNameEnum

主要用于:定义lmdb中的dbName

public enum LmdbNameEnum {//点位状态PointStatus("pointStatus");private String dbName;LmdbNameEnum(String dbName) {this.dbName = dbName;}public String getDbName() {return dbName;}@Overridepublic String toString() {return "LmdbNameEnum{" + "dbName=" + dbName + '}';}
}

4、Demo测试:LmdbController

package com.jack.maintain.controller;import com.jack.framework.json.resp.BaseResp;
import com.jack.maintain.cache.LmdbService;
import com.jack.maintain.enums.LmdbNameEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;import java.util.Map;@Controller
@RequestMapping(value = "/lmdb")
public class LmdbController{@Autowiredprivate LmdbService lmdbOperation;@RequestMapping(value = "setPoint/{point}",method = RequestMethod.GET)@ResponseBodypublic BaseResp setPoint(@PathVariable("point") String point){lmdbOperation.putValueToDb(LmdbNameEnum.PointStatus.getDbName(),point,point);return BaseResp.success("设值成功");}@RequestMapping(value = "getPoint/{point}",method = RequestMethod.GET)@ResponseBodypublic BaseResp getPoint(@PathVariable("point") String point){String val = lmdbOperation.getValueByKey(LmdbNameEnum.PointStatus.getDbName(),point);return BaseResp.success("成功",val);}@RequestMapping(value = "getPointCount",method = RequestMethod.GET)@ResponseBodypublic BaseResp getPointCount(){long count = lmdbOperation.getDbCount(LmdbNameEnum.PointStatus.getDbName());return BaseResp.success("成功",count);}@RequestMapping(value = "getPointList",method = RequestMethod.GET)@ResponseBodypublic BaseResp getDbVal(){Map<String,String> resultMap = lmdbOperation.getAllValueByDbName(LmdbNameEnum.PointStatus.getDbName());return BaseResp.success("成功",resultMap);}}

测试结果:

插入值:

获取值:


配置文件中定义的lmdb数据路径:

资源补全:(相关的公共方法类)

BaseResp.java(接口统一返回封装类)


import java.util.List;import com.jack.framework.json.JsonMsgUtil;
import com.fasterxml.jackson.annotation.JsonView;import lombok.Data;
import lombok.experimental.Accessors;/*** @Description: 基础返回类* @date 2018年5月21日 下午9:28:00*/
@Data
@Accessors(chain = true)
public class BaseResp {public interface DefaultJsonView {};@JsonView(DefaultJsonView.class)private boolean rs;@JsonView(DefaultJsonView.class)private int code;@JsonView(DefaultJsonView.class)private String msg;@JsonView(DefaultJsonView.class)private Object data;@JsonView(DefaultJsonView.class)private List<?> datas;public BaseResp() {this(0);}public BaseResp(int code) {this.code = code;}public BaseResp(int code, String msg) {this.code = code;this.msg = msg;}public String getMsg() {if (msg == null) {this.msg = JsonMsgUtil.getMsg(code);}if (this.msg == "") {this.msg = JsonMsgUtil.getMsg(9999);}return msg;}public boolean getRs() {rs = code == 0;return rs;}public boolean isRs() {rs = code == 0;return rs;}public static boolean isSuccess(BaseResp resp) {return resp.isRs();}/*** 功能描述:请求成功* @param filePath */public static BaseResp success(String msg) {BaseResp r = new BaseResp(0);r.setMsg(msg);return r;}//public static BaseResp success(String msg, Object data) {BaseResp r = new BaseResp(0);r.setMsg(msg);r.setData(data);return r;}public static BaseResp success(String msg, List<?> datas) {BaseResp r = new BaseResp(0);r.setMsg(msg);r.setDatas(datas);return r;}/*** 功能描述:参数出错*/public static BaseResp paramsError(String msg) {BaseResp r = new BaseResp(100);r.setMsg(msg);return r;}/*** 功能描述:验证出错*/public static BaseResp validError(String msg) {BaseResp r = new BaseResp(101);r.setMsg(msg);return r;}/*** 功能描述:逻辑判断出错*/public static BaseResp logicError(String msg) {BaseResp r = new BaseResp(102);r.setMsg(msg);return r;}/*** 功能描述:未登录*/public static BaseResp invalidLogin(String url) {BaseResp r = new BaseResp(9888);r.data = url;return r;}/*** 功能描述:无权限*/public static BaseResp invalidPerms(String msg) {BaseResp r = new BaseResp(9889);r.setMsg(msg);return r;}}

JsonMsgUtil.java(获取.properties文件属性的工具类)

package com.jack.framework.json;import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;import lombok.extern.slf4j.Slf4j;/*** 功能说明:资源工具类*/
@Slf4j
public final class JsonMsgUtil {private static Properties propertie = new Properties();private static String DEFAULT_MESSAGE = "";static {try {propertie = PropertiesLoaderUtils.loadProperties(new PathMatchingResourcePatternResolver().getResource("classpath:conf/json-msg.properties"));} catch (IOException e1) {String s = "Load resource file failed.";log.error(s);}}public static String getMsg(String key) {String message = propertie.getProperty(key, DEFAULT_MESSAGE);try {message = new String(message.getBytes("UTF-8"), "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();return DEFAULT_MESSAGE;}return message;}public static String getMsg(int key) {String message = propertie.getProperty("" + key, DEFAULT_MESSAGE);try {message = new String(message.getBytes("UTF-8"), "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();return DEFAULT_MESSAGE;}return message;}}

json-msg.properties(定义系统的统一返回码)
通常中文需要转成Unicode格式

##################
#JSON MSG
#返回码规划如下
#100    --默认参数异常
#1XXX --通用错误异常
#2XXX --业务模块异常
#3XXX --API模块异常#8XXX --管理模块异常
#9XXX --系统异常
############################################正常############################
0=成功##########################业务模块异常############################
#2X0X--业务通用模块
2001=文件上传失败
2002=业务参数异常
2003=你无权操作##########################API模块异常############################
3999=时间戳错误
3998=随机码错误
3997=签名错误3000=未登录或已失效,请重新登录##########################系统异常############################
9400=无效请求
9404=非法请求
9405=方法不被允许
9406=无法接受
9415=不支持的媒体类型
9500=执行异常9900=运行时异常
9901=空值异常
9902=数据类型转换异常
9903=IO异常
9904=未知方法异常
9905=数组越界异常9888=未登录或已失效,请重新登录
9889=权限不足9997=Json格式错误
9998=数据格式错误
9999=系统异常

Java 集成LMDB相关推荐

  1. 【JAVA零基础入门系列】Day2 Java集成开发环境IDEA

    [JAVA零基础入门系列](已完结)导航目录 Day1 开发环境搭建 Day2 Java集成开发环境IDEA Day3 Java基本数据类型 Day4 变量与常量 Day5 Java中的运算符 Day ...

  2. 6.Java集成开发环境

    转载请保留原文链接: http://dashidan.com/article/java/basic/6.html 6.Java集成开发环境 工欲善其事, 必先利其器.--<论语·卫灵公篇> ...

  3. Groovy与Java集成常见的坑--转

    https://yq.aliyun.com/articles/2357 groovy特性 Groovy是一门基于JVM的动态语言,同时也是一门面向对象的语言,语法上和Java非常相似.它结合了Pyth ...

  4. Groovy与Java集成常见的坑

    groovy特性 Groovy是一门基于JVM的动态语言,同时也是一门面向对象的语言,语法上和Java非常相似.它结合了Python.Ruby和Smalltalk的许多强大的特性,Groovy 代码能 ...

  5. 大数据之mongodb -- (2)java集成 MongoDB 3.2,使用Spring-data-mongodb进行集成

    Java集成MongoDB有很多方式,可以直接用mongodb的java驱动程序来发送语句到mongodb服务器,也可以用第三方的工具包来做. (1) 选择版本 选择的就是springdata集成的m ...

  6. snmp与java集成_轻松地与Java完全集成

    snmp与java集成 这里是如何不使用SQL,HQL,PHP,ASP,HTML,CSS或Javascript而是使用Vaadin的UI层和Speedment Stream ORM完全依赖Java编写 ...

  7. java 集成开发工具_最好的Java开发人员测试和集成工具

    java 集成开发工具 通过从您的应用程序学习企业APM产品,发现更快,更有效的性能监控. 参加AppDynamics APM导览! 无论您是刚刚起步还是已经从事了一段时间,使用正确的工具进行编程都可 ...

  8. java集成lucene_将Lucene搜索集成到应用程序中

    java集成lucene 本文是我们名为" Apache Lucene基础知识 "的学院课程的一部分. 在本课程中,您将了解Lucene. 您将了解为什么这样的库很重要,然后了解L ...

  9. java jquery_jQuery数据表和Java集成

    java jquery jQuery DataTables是一个开放源代码插件,用于在浏览器中创建表. 它具有许多功能,例如排序,服务器端处理, JQUERY UI主题滚动. 该插件的下载链接: ht ...

  10. jQuery数据表和Java集成

    jQuery DataTables是一个开放源代码插件,用于在浏览器中创建表. 它具有许多功能,例如排序,服务器端处理, JQUERY UI主题滚动. 该插件的下载链接: http://www.dat ...

最新文章

  1. java i 底层原理,《Java基础知识》Java Hash底层原理
  2. Java 基础学习-链接
  3. 《BI项目笔记》数据源视图设置
  4. if mybatis or test_真赞!IDEA中这么玩MyBatis,让编码速度飞起
  5. 金融matlab创建3x3数组,Matlatb金融时间序列工具箱——建立金融时间序列
  6. AMPL—快速了解,秒懂它。
  7. 云算子矩阵计算机,《CASIOfx-5800P矩阵编程计算器测量程序集锦梁宝禄.pdf》-支持高清全文免费浏览-max文档...
  8. 反转链表-递归反转法
  9. 全国高级项目经理人数知多少?(数据统计截止2013年6月22日)
  10. 路由器怎么用自己的笔记本电脑进行配置
  11. wifi6连接不上个别wifi
  12. 苹果Mac 无法读写NTFS格式的U盘或移动硬盘?一次解决
  13. 备忘录莫名其妙的没了_华为手机总是多出莫名其妙的照片?一键找到源头,教你彻底删除...
  14. 水星路由器wan口ip显示0_路由器wan口ip地址显示0.0.0.0怎么办
  15. OFDM和F-OFDM的功率谱与峰均功率比仿真
  16. Marvell校招新增数字后端工程师岗位
  17. 好用的工具推荐-excel插件
  18. 聊聊开源聊天软件oim-fx
  19. 分布式文件系统之冗余设计(电脑坏了怎么办)
  20. Novell的Suse Linux常用命令举例讲

热门文章

  1. 专访Wunderlist主设计师Jan Martin:永远不要盲目跟风流行趋势
  2. python colour-science 绘制CIE 1976色度图
  3. Stimulsoft Dashboards.WEB 2022.2.3 Crack
  4. 数字视频广播字幕系统(第6.7章)
  5. Odin Inspector 系列教程 --- 初识Odin序列化
  6. FastDFS配置文件
  7. 需求分解与需求跟踪矩阵
  8. Linux基础学习记录
  9. iperf 服务端发送数据_iperf使用指南
  10. Win10 dell驱动触摸板安装