Skip to content

Commit

Permalink
优化 records 类的编码方式
Browse files Browse the repository at this point in the history
  • Loading branch information
vnobo committed Oct 30, 2023
1 parent 16d2c29 commit 9f3f40d
Show file tree
Hide file tree
Showing 15 changed files with 39 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* @author Alex bob(<a href="https://github.com/vnobo">...</a>)
* @author Alex bob(<a href="https://github.com/vnobo">Alex Bob</a>)
*/
@SpringBootApplication
public class BootApplication {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ public abstract class AbstractDatabase extends AbstractService {

@Value("${spring.codec.max-in-memory-size:256kb}")
private DataSize maxInMemorySize;

protected R2dbcEntityTemplate entityTemplate;
protected DatabaseClient databaseClient;
protected R2dbcConverter r2dbcConverter;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.platform.boot.commons.base;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
Expand All @@ -20,14 +19,6 @@
* If the cacheManager is null, a new ConcurrentMapCache is created.
*
* @author <a href="https://github.com/vnobo">Alex bob</a>
* @see InitializingBean
* @see Cache
* @see CacheManager
* @see ConcurrentMapCache
* @see Optional
* @see ObjectMapper
* @see Log4j2
* @since 1.0.0
*/
public abstract class AbstractService implements InitializingBean {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,43 +41,44 @@ public final class ContextUtils implements Serializable {
ContextUtils.USERS_SERVICE = usersService;
}

public static String cacheKey(Object... objects) {
public static StringJoiner cacheKey(Object... objects) {
// Convert objects to a map using ObjectMapper
StringBuilder keyBuilder = new StringBuilder();
StringJoiner keyBuilder = new StringJoiner("&");
for (Object object : objects) {
if (object instanceof Pageable pageable) {
keyBuilder.append(applySort(pageable.getSort()));
keyBuilder.append("&page=").append(pageable.getPageNumber());
keyBuilder.append("&size=").append(pageable.getPageSize());
keyBuilder.append("&offset=").append(pageable.getOffset());
keyBuilder.merge(applySort(pageable.getSort()));
keyBuilder.add("page=" + pageable.getPageNumber());
keyBuilder.add("size=" + pageable.getPageSize());
keyBuilder.add("offset=" + pageable.getOffset());
continue;
}
// Convert object to a map using ObjectMapper
Map<String, Object> objectMap = com.platform.boot.commons.utils.BeanUtils.beanToMap(object, true);
Map<String, Object> objectMap = com.platform.boot.commons.utils.BeanUtils
.beanToMap(object, true);
// Check if the object map is empty
if (ObjectUtils.isEmpty(objectMap)) {
// Append the class name of the object to the key builder
keyBuilder.append(object.getClass().getName()).append("&");
keyBuilder.add(object.getClass().getName());
continue;
}
// Append each key-value pair from the object map to the key builder
objectMap.forEach((k, v) -> keyBuilder.append(k).append("=").append(v).append("&"));
objectMap.forEach((k, v) -> keyBuilder.add(k + "=" + v));
}
// Return the final cache key as a string
return keyBuilder.toString();
return keyBuilder;
}

private static String applySort(Sort sort) {
private static StringJoiner applySort(Sort sort) {
StringJoiner sortKey = new StringJoiner("&");
if (sort == null || sort.isUnsorted()) {
return "";
return sortKey;
}
StringJoiner sortSql = new StringJoiner(", ");
for (Sort.Order order : sort) {
String sortedPropertyName = order.getProperty();
String sortedProperty = order.isIgnoreCase() ? "lower(" + sortedPropertyName + ")" : sortedPropertyName;
sortSql.add("&" + sortedProperty + "=" + (order.isAscending() ? "asc" : "desc"));
sortKey.add(sortedProperty + "=" + (order.isAscending() ? "asc" : "desc"));
}
return sortSql.toString();
return sortKey;
}

public static Mono<SecurityDetails> securityDetails() {
Expand All @@ -102,12 +103,12 @@ public static <T> Mono<T> userAuditorSerializable(T obejct) {
return Mono.just(obejct);
} catch (IllegalAccessException | InvocationTargetException e) {
return Mono.error(RestServerException.withMsg(
"User auditor serialization getWriteMethod invoke error", e));
"User auditor serialization getWriteMethod invoke error!", e));
}
});
} catch (IllegalAccessException | InvocationTargetException e) {
return Mono.error(RestServerException.withMsg(
"User auditor serialization getReadMethod invoke error", e));
"User auditor serialization getReadMethod invoke error!", e));
}
});
return propertyFlux.then(Mono.just(obejct));
Expand All @@ -116,7 +117,7 @@ public static <T> Mono<T> userAuditorSerializable(T obejct) {
public static String nextId() {
if (ObjectUtils.isEmpty(SNOW_FLAKE)) {
throw RestServerException.withMsg(
"Snowflake not found", "Snowflake server is not found, init snowflake first.");
"Snowflake not found!", "Snowflake server is not found, init snowflake first.");
}
return SNOW_FLAKE.nextIdStr();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ public final class CriteriaUtils {
* @return the SQL query with applied pagination
*/
public static String applyPage(Pageable pageable) {
String orderSql = applySort(pageable.getSort(), null);
return String.format(orderSql + " limit %d offset %d", pageable.getPageSize(), pageable.getOffset());
return applySort(pageable.getSort(), null);
}

/**
Expand All @@ -54,7 +53,7 @@ public static String applySort(Sort sort, String prefix) {
if (sort == null || sort.isUnsorted()) {
return "";
}
StringJoiner sortSql = new StringJoiner(" , ");
StringJoiner sortSql = new StringJoiner(", ");
sort.iterator().forEachRemaining((o) -> {
String sortedPropertyName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, o.getProperty());
String sortedProperty = o.isIgnoreCase() ? "lower(" + sortedPropertyName + ")" : sortedPropertyName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class LoggersService extends AbstractDatabase {

public Flux<Logger> search(LoggerRequest request, Pageable pageable) {
//Create a cache key based on the given request and pageable parameters
String cacheKey = ContextUtils.cacheKey(request, pageable);
var cacheKey = ContextUtils.cacheKey(request, pageable);
//Create a query based on the given request and pageable parameters
Query query = Query.query(request.toCriteria()).with(pageable);
//Return the query with the cache key and Logger class
Expand All @@ -31,7 +31,7 @@ public Flux<Logger> search(LoggerRequest request, Pageable pageable) {

public Mono<Page<Logger>> page(LoggerRequest request, Pageable pageable) {
//Create a cache key based on the request
String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
//Create a query based on the request
Query query = Query.query(request.toCriteria());
//Collect a list of Loggers based on the request and pageable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public class MenusService extends AbstractDatabase {
* @return a Flux of Menus with the search criteria
*/
public Flux<Menu> search(MenuRequest request) {
String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
Query query = Query.query(request.toCriteria()).sort(Sort.by("sort"));
return this.queryWithCache(cacheKey, query, Menu.class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* @param token Token used for authentication
* @param expires Expiry time of the token in seconds
* @param lastAccessTime Last access time of the token in epoch seconds
* @author Alex bob
* @author Alex bob(<a href="https://github.com/vnobo">Alex Bob</a>)
*/
public record AuthenticationToken(String token, Long expires, Long lastAccessTime) implements Serializable {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ public class GroupsService extends AbstractDatabase {
private final GroupsRepository groupsRepository;

public Flux<Group> search(GroupRequest request, Pageable pageable) {
String cacheKey = ContextUtils.cacheKey(request, pageable);
var cacheKey = ContextUtils.cacheKey(request, pageable);
Query query = Query.query(request.toCriteria()).with(pageable);
return super.queryWithCache(cacheKey, query, Group.class).flatMap(ContextUtils::userAuditorSerializable);
}

public Mono<Page<Group>> page(GroupRequest request, Pageable pageable) {
String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
Query query = Query.query(request.toCriteria());
var searchMono = this.search(request, pageable).collectList();
var countMono = this.countWithCache(cacheKey, query, Group.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class GroupAuthoritiesService extends AbstractDatabase {

public Flux<GroupAuthority> search(GroupAuthorityRequest request, Pageable pageable) {

String cacheKey = ContextUtils.cacheKey(request, pageable);
var cacheKey = ContextUtils.cacheKey(request, pageable);
Query query = Query.query(request.toCriteria()).with(pageable);

return super.queryWithCache(cacheKey, query, GroupAuthority.class)
Expand All @@ -42,7 +42,7 @@ public Mono<Page<GroupAuthority>> page(GroupAuthorityRequest request, Pageable p

var searchMono = this.search(request, pageable).collectList();

String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
Query query = Query.query(request.toCriteria());
var countMono = super.countWithCache(cacheKey, query, GroupAuthority.class);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class GroupMembersService extends AbstractDatabase {
private final GroupMembersRepository memberRepository;

public Flux<GroupMemberResponse> search(GroupMemberRequest request, Pageable pageable) {
String cacheKey = ContextUtils.cacheKey(request, pageable);
var cacheKey = ContextUtils.cacheKey(request, pageable);
ParamSql paramSql = request.toParamSql();
String query = request.querySql() + paramSql.whereSql() + CriteriaUtils.applyPage(pageable);
return super.queryWithCache(cacheKey, query, paramSql.params(), GroupMemberResponse.class);
Expand All @@ -32,7 +32,7 @@ public Flux<GroupMemberResponse> search(GroupMemberRequest request, Pageable pag
public Mono<Page<GroupMemberResponse>> page(GroupMemberRequest request, Pageable pageable) {
var searchMono = this.search(request, pageable).collectList();

String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
ParamSql paramSql = request.toParamSql();
String query = request.countSql() + paramSql.whereSql();
var countMono = this.countWithCache(cacheKey, query, paramSql.params());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class TenantsService extends AbstractDatabase {
* @return 包含租户信息的Flux对象
*/
public Flux<Tenant> search(TenantRequest request, Pageable pageable) {
String cacheKey = ContextUtils.cacheKey(request, pageable);
var cacheKey = ContextUtils.cacheKey(request, pageable);
// 使用Java 17中的var关键字,类型推断更加简洁
var query = Query.query(request.toCriteria()).with(pageable);
// 使用Java 17中的新方法of,避免使用Tuple2
Expand All @@ -42,7 +42,7 @@ public Flux<Tenant> search(TenantRequest request, Pageable pageable) {
* @return 包含租户信息的Mono对象
*/
public Mono<Page<Tenant>> page(TenantRequest request, Pageable pageable) {
String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
Query query = Query.query(request.toCriteria());
// 使用Java 17中的var关键字,类型推断更加简洁
var tenantsMono = this.search(request, pageable).collectList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class TenantMembersService extends AbstractDatabase {
* @return a flux of TenantMemberResponse objects matching the search criteria
*/
public Flux<TenantMemberResponse> search(TenantMemberRequest request, Pageable pageable) {
String cacheKey = ContextUtils.cacheKey(request, pageable);
var cacheKey = ContextUtils.cacheKey(request, pageable);
ParamSql paramSql = request.toParamSql();
String query = request.querySql() + paramSql.whereSql() + CriteriaUtils.applyPage(pageable, "a");
return super.queryWithCache(cacheKey, query, paramSql.params(), TenantMemberResponse.class);
Expand All @@ -49,7 +49,7 @@ public Flux<TenantMemberResponse> search(TenantMemberRequest request, Pageable p
public Mono<Page<TenantMemberResponse>> page(TenantMemberRequest request, Pageable pageable) {
var searchMono = this.search(request, pageable).collectList();

String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
ParamSql paramSql = request.toParamSql();
String query = request.countSql() + paramSql.whereSql();
Mono<Long> countMono = this.countWithCache(cacheKey, query, paramSql.params());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class UsersService extends AbstractDatabase {
private final UsersRepository usersRepository;

public Flux<UserResponse> search(UserRequest request, Pageable pageable) {
String cacheKey = ContextUtils.cacheKey(request, pageable);
var cacheKey = ContextUtils.cacheKey(request, pageable);
ParamSql paramSql = QueryJson.queryJson(request.getQuery());
String query = "select * from se_users" + paramSql.whereSql() + CriteriaUtils.applyPage(pageable);
return super.queryWithCache(cacheKey, query, paramSql.params(), UserResponse.class)
Expand All @@ -38,7 +38,7 @@ public Flux<UserResponse> search(UserRequest request, Pageable pageable) {
public Mono<Page<UserResponse>> page(UserRequest request, Pageable pageable) {
var searchMono = this.search(request, pageable).collectList();

String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
ParamSql paramSql = QueryJson.queryJson(request.getQuery());
String query = "select count(*) from se_users" + paramSql.whereSql();
var countMono = super.countWithCache(cacheKey, query, paramSql.params());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class UserAuthoritiesService extends AbstractDatabase {
private final UserAuthoritiesRepository userAuthoritiesRepository;

public Flux<UserAuthority> search(UserAuthorityRequest request) {
String cacheKey = ContextUtils.cacheKey(request);
var cacheKey = ContextUtils.cacheKey(request);
Query query = Query.query(request.toCriteria());
return super.queryWithCache(cacheKey, query, UserAuthority.class)
.flatMap(ContextUtils::userAuditorSerializable);
Expand Down

0 comments on commit 9f3f40d

Please sign in to comment.