初始化

This commit is contained in:
chenyawei 2025-03-18 09:02:50 +08:00
parent 66f69172a8
commit 6c278b02cf
16 changed files with 745 additions and 3 deletions

21
pom.xml
View File

@ -32,6 +32,26 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Client依赖包 -->
<dependency>
<groupId>com.vesoft</groupId>
<artifactId>client</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.nebula-contrib</groupId>
<artifactId>ngbatis</artifactId>
<version>2.0.0-beta</version>
<exclusions>
<exclusion>
<groupId>com.vesoft</groupId>
<artifactId>client</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
@ -44,6 +64,7 @@
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</path>
</annotationProcessorPaths>
</configuration>

View File

@ -1,13 +1,37 @@
package com.idata.tools.ngbatisdemo;
import com.idata.tools.ngbatisdemo.dao.UserDao;
import com.idata.tools.ngbatisdemo.pojo.User;
import com.idata.tools.ngbatisdemo.service.UserService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
import java.util.List;
/**
* @author: ChenYaWei
*/
@SpringBootApplication(scanBasePackages = { "org.nebula", "com.idata.tools.ngbatisdemo"}, exclude = DataSourceAutoConfiguration.class)
//@SpringBootApplication
public class NgbatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(NgbatisDemoApplication.class, args);
ConfigurableApplicationContext context = SpringApplication.run(NgbatisDemoApplication.class, args);
UserService userService = context.getBean(UserService.class);
userService.demos();
UserDao userDao = context.getBean(UserDao.class);
List<String> list = userDao.selectListString();
list.forEach(System.out::println);
User user = new User();
user.setName("james");
System.out.println(userDao.selectUser());
System.out.println("===============");
System.out.println(userDao.selectListString());
}
}

View File

@ -0,0 +1,32 @@
//package com.idata.tools.ngbatisdemo.config;
//
//import lombok.Data;
//import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
//import org.springframework.context.annotation.Configuration;
//
//
//@Configuration
//@ConfigurationProperties(prefix = "nebula")
//@EnableConfigurationProperties(NebulaGraphProperties.class)
//@Data
////@RefreshScope
//public class NebulaGraphProperties {
// private String userName;
// private String password;
// /**
// * 格式ip:port
// */
// private String hostAddresses;
// private int minConnSize;
// private int maxConnSize;
// private int timeout;
// private int idleTime;
// private String spaceName;
// private Integer limit;
// private Boolean isMatch;
// private Boolean cache;
// private int cacheTime;
// private int startNum;
// private int startLimit;
//}

View File

@ -0,0 +1,36 @@
//package com.idata.tools.ngbatisdemo.config;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
///**
// *
// * 配置全局唯一session链接
// **/
//@Configuration
//public class NebulaSessionPoolConfig {
//
// private final NebulaGraphProperties nebulaGraphProperties;
//
// @Autowired
// public NebulaSessionPoolConfig(NebulaGraphProperties nebulaGraphProperties) {
// this.nebulaGraphProperties = nebulaGraphProperties;
// }
//
//// @Bean
//// public Session session() throws Exception {
//// SessionPool sessionPool = new SessionPool(5, 2, nebulaGraphProperties.getHostAddresses(),
//// nebulaGraphProperties.getUserName(), nebulaGraphProperties.getPassword());
//// return sessionPool.borrow(true);
//// }
//
// @Bean
// public SessionPool sessionPool() throws Exception {
// return new SessionPool(nebulaGraphProperties.getMaxConnSize(),
// nebulaGraphProperties.getMinConnSize(), nebulaGraphProperties.getHostAddresses(),
// nebulaGraphProperties.getUserName(), nebulaGraphProperties.getPassword());
// }
//
//
//}

View File

@ -0,0 +1,120 @@
//package com.idata.tools.ngbatisdemo.config;
//
//
//import com.idata.tools.ngbatisdemo.log.YLogger;
//import com.idata.tools.ngbatisdemo.log.YLoggerFactory;
//import com.vesoft.nebula.client.graph.NebulaPoolConfig;
//import com.vesoft.nebula.client.graph.data.HostAddress;
//import com.vesoft.nebula.client.graph.exception.AuthFailedException;
//import com.vesoft.nebula.client.graph.exception.ClientServerIncompatibleException;
//import com.vesoft.nebula.client.graph.exception.IOErrorException;
//import com.vesoft.nebula.client.graph.exception.NotValidConnectionException;
//import com.vesoft.nebula.client.graph.net.NebulaPool;
//import com.vesoft.nebula.client.graph.net.Session;
//
//import javax.annotation.PreDestroy;
//import java.net.UnknownHostException;
//import java.util.Arrays;
//import java.util.List;
//import java.util.Queue;
//import java.util.concurrent.LinkedBlockingQueue;
//import java.util.stream.Collectors;
//
///**
// * @author
// * SessionPool
// */
//public class SessionPool {
//
// private final YLogger logger = YLoggerFactory.getLogger(SessionPool.class);
// /**
// * 创建连接池
// *
// * @param maxCountSession 默认创建连接数
// * @param minCountSession 最大创建连接数
// * @param hostAndPort 机器端口列表
// * @param userName 用户名
// * @param passWord 密码
// * @throws UnknownHostException
// * @throws NotValidConnectionException
// * @throws IOErrorException
// * @throws AuthFailedException
// */
// public SessionPool(int maxCountSession, int minCountSession, String hostAndPort, String userName, String passWord) throws UnknownHostException, NotValidConnectionException, IOErrorException, AuthFailedException, ClientServerIncompatibleException {
// this.minCountSession = minCountSession;
// this.maxCountSession = maxCountSession;
// this.userName = userName;
// this.passWord = passWord;
// this.queue = new LinkedBlockingQueue<>(minCountSession);
// this.pool = this.initGraphClient(hostAndPort, maxCountSession, minCountSession);
// initSession();
// }
//
// public Session borrow(Boolean reconnect) {
// Session se = queue.poll();
// if (se != null) {
// return se;
// }
// try {
// return this.pool.getSession(userName, passWord, reconnect);
// } catch (Exception e) {
// logger.error(this.getClass(), "borrow", null,"execute borrow session fail", e);
// throw new RuntimeException(e);
// }
// }
//
// @PreDestroy
// public void release() {
// Queue<Session> queue = this.queue;
// for (Session se : queue) {
// if (se != null) {
// boolean success = this.queue.offer(se);
// if (!success) {
// se.release();
// }
// }
// }
// }
//
// public void close() {
// this.pool.close();
// }
//
// private void initSession() throws NotValidConnectionException, IOErrorException, AuthFailedException, ClientServerIncompatibleException {
// for (int i = 0; i < minCountSession; i++) {
// queue.offer(this.pool.getSession(userName, passWord, true));
// }
// }
//
// private NebulaPool initGraphClient(String hostAndPort, int maxConnSize, int minCount) throws UnknownHostException {
// List<HostAddress> hostAndPorts = getGraphHostPort(hostAndPort);
// NebulaPool pool = new NebulaPool();
// NebulaPoolConfig nebulaPoolConfig = new NebulaPoolConfig();
// nebulaPoolConfig = nebulaPoolConfig.setMaxConnSize(maxConnSize);
// nebulaPoolConfig = nebulaPoolConfig.setMinConnSize(minCount);
// nebulaPoolConfig = nebulaPoolConfig.setIdleTime(1000 * 600);
// pool.init(hostAndPorts, nebulaPoolConfig);
// return pool;
// }
//
// private List<HostAddress> getGraphHostPort(String hostAndPort) {
// String[] split = hostAndPort.split(",");
// return Arrays.stream(split).map(item -> {
// String[] splitList = item.split(":");
// return new HostAddress(splitList[0], Integer.parseInt(splitList[1]));
// }).collect(Collectors.toList());
// }
//
// private Queue<Session> queue;
//
// private String userName;
//
// private String passWord;
//
// private int minCountSession;
//
// private int maxCountSession;
//
// private NebulaPool pool;
//
//}

View File

@ -0,0 +1,31 @@
package com.idata.tools.ngbatisdemo.controller;
import com.idata.tools.ngbatisdemo.pojo.User;
import com.idata.tools.ngbatisdemo.service.UserService;
import com.idata.tools.ngbatisdemo.service.UserServiceImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @author: ChenYawei
* @date: 2025/3/17 16:24
*/
@RestController
@RequestMapping("/test")
public class UserController {
private final UserServiceImpl userService;
public UserController(UserServiceImpl userService) {
this.userService = userService;
}
@GetMapping("/user")
public String test() {
userService.demos();
return "hello";
}
}

View File

@ -0,0 +1,28 @@
package com.idata.tools.ngbatisdemo.dao;
import com.idata.tools.ngbatisdemo.pojo.User;
import org.nebula.contrib.ngbatis.proxy.NebulaDaoBasic;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* @description: xxx
* @author: ChenYaWei
* @date: 2025/3/17 15:24
*/
@Component
public interface UserDao extends NebulaDaoBasic<User, String> {
// new features from v1.2.0
Integer returnAge(@Param("User")User User);
User selectUser();
User selectByUser(User user);
List<User> selectAgeGt(Integer age);
List<String> selectListString();
List<Map> selectUsersMap();
Map<String, Object> selectTriple();
}

View File

@ -0,0 +1,236 @@
package com.idata.tools.ngbatisdemo.log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
/**
* @Description: Y 日志
* @Author: li-chuan-guo
* @Date: 2024-09-24 14:52
**/
public class YLogger {
private final Logger logger;
private final static String SPLIT_STR = "&";
private static final String FQCN = YLogger.class.getName();
public YLogger(Class<?> clazz) {
this.logger = LoggerFactory.getLogger(clazz);
}
/**
* 信息日志
*
* @param clazz 类信息必填
* @param methodName 方法名称 必填
* @param paramStr 参数串非必填
* @param responseStr 响应串非必填
* @param message 日志信息必填
* @param extraArgs 额外的参数非必填
*/
public void info(Class<?> clazz, String methodName, String paramStr, String responseStr, String message,
String... extraArgs) {
try {
String className = clazz.getName();
StringBuilder sb = new StringBuilder();
sb.append(className).append(SPLIT_STR);
sb.append(methodName == null ? "" : methodName).append(SPLIT_STR);
sb.append(paramStr == null ? "" : paramStr).append(SPLIT_STR);
sb.append(responseStr == null ? "" : responseStr).append(SPLIT_STR);
sb.append(message == null ? "" : message).append(SPLIT_STR);
if (extraArgs != null) {
// extraArg 合并成String后拼接
sb.append(String.join(",", extraArgs));
}
if (this.logger instanceof LocationAwareLogger) {
((LocationAwareLogger) this.logger).log(null, FQCN, LocationAwareLogger.INFO_INT, sb.toString(),
null, null);
return;
}
logger.info(sb.toString());
} catch (Exception e) {
logger.info("log info fail");
}
}
/**
* 入参打印
* @param clazz 类信息必填
* @param methodName 方法名称 必填
* @param paramStr 参数串非必填
* @param extraArgs 额外的参数非必填
*/
public void info(Class<?> clazz, String methodName, String paramStr, String extraArgs) {
try {
String className = clazz.getName();
StringBuilder sb = new StringBuilder();
sb.append(className).append(SPLIT_STR);
sb.append(methodName == null ? "" : methodName).append(SPLIT_STR);
sb.append(paramStr == null ? "" : paramStr).append(SPLIT_STR);
if (extraArgs != null) {
// extraArg 合并成String后拼接
sb.append(String.join(",", extraArgs));
}
if (this.logger instanceof LocationAwareLogger) {
((LocationAwareLogger) this.logger).log(null, FQCN, LocationAwareLogger.INFO_INT, sb.toString(),
null, null);
return;
}
logger.info(sb.toString());
} catch (Exception e) {
logger.info("log info fail");
}
}
/**
* 跟踪日志
*
* @param clazz 类信息必填
* @param methodName 方法名称 必填
* @param paramStr 参数串非必填
* @param extraArgs 额外的参数非必填
*/
public void trace(Class<?> clazz, String methodName, String paramStr, String... extraArgs) {
try {
String className = clazz.getName();
StringBuilder sb = new StringBuilder();
sb.append(className).append(SPLIT_STR);
sb.append(methodName == null ? "" : methodName).append(SPLIT_STR);
sb.append(paramStr == null ? "" : paramStr).append(SPLIT_STR);
// extraArgs 中添加参数 trace
if (extraArgs != null) {
// extraArg 合并成String后拼接;
sb.append("trace,").append(String.join(",", extraArgs));
} else {
sb.append("trace");
}
if (this.logger instanceof LocationAwareLogger) {
((LocationAwareLogger) this.logger).log(null, FQCN, LocationAwareLogger.INFO_INT, sb.toString(),
null, null);
return;
}
logger.info(sb.toString());
} catch (Exception e) {
logger.info("log info fail");
}
}
/**
* 错误日志
*
* @param clazz 类信息必填
* @param methodName 方法名称 必填
* @param paramStr 参数串 必填
* @param errMsg 异常信息 必填
* @param e 异常堆栈 非必填
*/
public void error(Class<?> clazz, String methodName, String paramStr, String errMsg, Exception e) {
try {
String className = clazz.getName();
StringBuilder sb = new StringBuilder();
sb.append(className).append(SPLIT_STR);
sb.append(methodName == null ? "" : methodName).append(SPLIT_STR);
sb.append(paramStr == null ? "" : paramStr).append(SPLIT_STR);
sb.append(errMsg == null ? "" : errMsg).append(SPLIT_STR);
if (e != null) {
if (this.logger instanceof LocationAwareLogger) {
((LocationAwareLogger) this.logger).log(null, FQCN, LocationAwareLogger.ERROR_INT, sb.toString(),
null, e);
return;
}
logger.error(sb.toString(), e);
} else {
if (this.logger instanceof LocationAwareLogger) {
((LocationAwareLogger) this.logger).log(null, FQCN, LocationAwareLogger.ERROR_INT, sb.toString(),
null, null);
return;
}
logger.error(sb.toString());
}
} catch (Exception e2) {
logger.error("log error fail");
}
}
/**
* 错误日志
*
* @param clazz 类信息必填
* @param methodName 方法名称 必填
* @param paramStr 参数串 必填
* @param errMsg 异常信息 必填
*/
public void error(Class<?> clazz, String methodName, String paramStr, String errMsg) {
try {
String className = clazz.getName();
StringBuilder sb = new StringBuilder();
sb.append(className).append(SPLIT_STR);
sb.append(methodName == null ? "" : methodName).append(SPLIT_STR);
sb.append(paramStr == null ? "" : paramStr).append(SPLIT_STR);
sb.append(errMsg == null ? "" : errMsg);
if (this.logger instanceof LocationAwareLogger) {
((LocationAwareLogger) this.logger).log(null, FQCN, LocationAwareLogger.ERROR_INT, sb.toString(),
null, null);
return;
}
logger.error(sb.toString());
} catch (Exception e2) {
logger.error("log error fail");
}
}
/**
* 警告日志
*
* @param clazz 类信息必填
* @param methodName 方法名称 必填
* @param paramStr 参数串 必填
* @param warnMsg 警告信息 必填
* @param extraArgs 额外参数 非必填
*/
public void warn(Class<?> clazz, String methodName, String paramStr, String warnMsg, String... extraArgs) {
try {
String className = clazz.getName();
StringBuilder sb = new StringBuilder();
sb.append(className).append(SPLIT_STR);
sb.append(methodName == null ? "" : methodName).append(SPLIT_STR);
sb.append(paramStr == null ? "" : paramStr).append(SPLIT_STR);
sb.append(warnMsg == null ? "" : warnMsg);
if (extraArgs != null) {
sb.append(SPLIT_STR).append(String.join(",", extraArgs));
}
if (this.logger instanceof LocationAwareLogger) {
((LocationAwareLogger) this.logger).log(null, FQCN, LocationAwareLogger.WARN_INT, sb.toString(),
null, null);
return;
}
logger.warn(sb.toString());
} catch (Exception e) {
logger.warn("log warn fail");
}
}
public void debug(Class<?> clazz, String methodName, String paramStr, String debugMsg, String... extraArgs) {
try {
String className = clazz.getName();
StringBuilder sb = new StringBuilder();
sb.append(className).append(SPLIT_STR);
sb.append(methodName == null ? "" : methodName).append(SPLIT_STR);
sb.append(paramStr == null ? "" : paramStr).append(SPLIT_STR);
sb.append(debugMsg == null ? "" : debugMsg);
if (extraArgs != null) {
sb.append(SPLIT_STR).append(String.join(",", extraArgs));
}
if (this.logger instanceof LocationAwareLogger) {
((LocationAwareLogger) this.logger).log(null, FQCN, LocationAwareLogger.WARN_INT, sb.toString(),
null, null);
return;
}
logger.debug(sb.toString());
} catch (Exception e) {
logger.debug("log debug fail");
}
}
}

View File

@ -0,0 +1,21 @@
package com.idata.tools.ngbatisdemo.log;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @Description: y 系统日志工厂
* @Author: li-chuan-guo
* @Date: 2024-09-24 14:51
**/
@Component
public class YLoggerFactory {
private static final ConcurrentMap<Class<?>, YLogger> LOGGER_CACHE = new ConcurrentHashMap<>();
public static YLogger getLogger(Class<?> clazz) {
return LOGGER_CACHE.computeIfAbsent(clazz, YLogger::new);
}
}

View File

@ -0,0 +1,29 @@
package com.idata.tools.ngbatisdemo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @description:
* @author: ChenYawei
* @date: 2025/1/9 11:03
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "user")
public class User {
@Id
private String id;
private String name;
private String platform;
}

View File

@ -0,0 +1,33 @@
package com.idata.tools.ngbatisdemo.pojo;
import lombok.Data;
import org.nebula.contrib.ngbatis.annotations.DstId;
import org.nebula.contrib.ngbatis.annotations.SrcId;
import org.nebula.contrib.ngbatis.annotations.base.EdgeType;
import javax.persistence.Column;
import javax.persistence.Id;
/**
* @description:
* @author: ChenYawei
* @date: 2025/3/17 15:32
*/
@Data
@EdgeType(name = "user_follow_user")
public class UserFollowUser {
@Id
private Long rank;
@SrcId
private String srcId;
@DstId
private String dstId;
@Column(name = "extra_prop")
private String extraProp;
}

View File

@ -0,0 +1,20 @@
package com.idata.tools.ngbatisdemo.service;
import com.idata.tools.ngbatisdemo.pojo.User;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @description:
* @author: ChenYawei
* @date: 2025/3/17 16:24
*/
@Service
public interface UserService {
void demos();
}

View File

@ -0,0 +1,31 @@
package com.idata.tools.ngbatisdemo.service;
import com.idata.tools.ngbatisdemo.dao.UserDao;
import com.idata.tools.ngbatisdemo.pojo.User;
import org.springframework.stereotype.Service;
/**
* @description:
* @author: ChenYawei
* @date: 2025/3/17 15:28
*/
@Service
public class UserServiceImpl implements UserService{
private final UserDao userDao;
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void demos() {
User user = new User();
user.setId("12345678123456781234567812345678");
Integer insert = userDao.insert(user);
System.out.println(insert);
}
}

View File

@ -1 +0,0 @@
spring.application.name=ngbatis-demo

View File

@ -0,0 +1,20 @@
nebula:
ngbatis:
session-life-length: 300000 # since v1.1.2
check-fixed-rate: 300000 # since v1.1.2
# space name needs to be informed through annotations(@Space) or xml(space="test")
# default false(false: Session pool map will not be initialized)
use-session-pool: false # since v1.1.2
hosts: 172.16.20.2:9669, 172.16.20.4:9669, 172.16.20.5:9669
username: root
password: nebula
space: Y0210_TEST
pool-config:
min-conns-size: 2
max-conns-size: 4
timeout: 0
idle-time: 0
interval-idle: -1
wait-time: 0
min-cluster-health-rate: 1.0
enable-ssl: false

View File

@ -0,0 +1,61 @@
<mapper namespace="com.idata.tools.ngbatisdemo.dao.UserDao">
<!-- new features from v1.2.0 start -->
<nGQL id="include-test-value">
${myInt}
</nGQL>
<nGQL id="ngql-return-age">
RETURN @ng.include('include-test-value',{'myInt':age});
</nGQL>
<!--
The same as:
RETURN ${user.age};
You can try extracting more common and meaningful scripts.
-->
<select id="returnAge" resultType="java.lang.Integer">
@ng.include('ngql-return-age',user);
</select>
<!-- new features from v1.2.0 end -->
<select id="selectUser" resultType="com.idata.tools.ngbatisdemo.pojo.User">
match (v:user) return v.user.name as name, v.user.platform as platform limit 1000
</select>
<select id="selectAgeGt" resultType="com.idata.tools.ngbatisdemo.pojo.User">
MATCH (n: user)
WHERE n.user.age > $p0
RETURN n
LIMIT 100
</select>
<select id="selectByUser" resultType="com.idata.tools.ngbatisdemo.pojo.User">
MATCH (n: user)
WHERE n.user.name == $p0.name
RETURN n
LIMIT 100
</select>
<select id="selectListString" resultType="java.lang.String">
match (v:user) return v.user.name as name limit 100
</select>
<select id="selectUsersMap" resultType="java.util.Map">
match (v:user) return v.user.name as name, v.user.age as age limit 100
</select>
<select id="selectTriple" resultType="java.util.Map">
MATCH (n: user)-[r: user_follow_user]->(n2: user)
RETURN n, r, n2
LIMIT 100
</select>
<!--
More complex `nGQL` may need to be fully tested.
The two-layer object data structure of the project I am currently using is also satisfying.
`Path` is not yet supported because it can basically be handled by the `n, r, n2` structure in development.
-->
</mapper>