code optimize

This commit is contained in:
xiaoyu1 2018-07-03 16:56:45 +08:00
parent 47b87f453d
commit 58c7317e8a
42 changed files with 382 additions and 777 deletions

View File

@ -15,6 +15,7 @@
* along with this distribution; if not, see <http://www.gnu.org/licenses/>.
*
*/
package com.raincat.admin;
import org.springframework.boot.SpringApplication;
@ -23,14 +24,18 @@ import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurat
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
/**
* AdminApplication.
* @author xiaoyu
*/
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class AdminApplication {
public static void main(String[] args) {
/**
* bootstrap main.
* @param args args.
*/
public static void main(final String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
}

View File

@ -33,9 +33,9 @@ import java.lang.annotation.Target;
public @interface Permission {
/**
* 是否登录
* is login
*
* @return true 需要 false 不需要
* @return true
*/
boolean isLogin() default true;

View File

@ -15,6 +15,7 @@
* along with this distribution; if not, see <http://www.gnu.org/licenses/>.
*
*/
package com.raincat.admin.configuration;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
@ -49,46 +50,32 @@ import java.util.ServiceLoader;
import java.util.stream.StreamSupport;
/**
* <p>Description: .</p>
*
* AdminConfiguration.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/23 21:08
* @since JDK 1.8
*/
@Configuration
public class AdminConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
/* @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/login*//*").allowedOrigins("*");
registry.addMapping("/recover*//*").allowedOrigins("*");
registry.addMapping("/tx*//*").allowedOrigins("*");
}
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**");
}
};
}
@Configuration
static class SerializerConfiguration {
private final Environment env;
@Autowired
public SerializerConfiguration(Environment env) {
SerializerConfiguration(final Environment env) {
this.env = env;
}
@Bean
public ObjectSerializer objectSerializer() {
@ -96,29 +83,24 @@ public class AdminConfiguration {
SerializeProtocolEnum.acquireSerializeProtocol(env.getProperty("recover.serializer.support"));
final ServiceLoader<ObjectSerializer> objectSerializers =
ServiceBootstrap.loadAll(ObjectSerializer.class);
return StreamSupport.stream(objectSerializers.spliterator(), false)
.filter(objectSerializer ->
Objects.equals(objectSerializer.getScheme(),
serializeProtocolEnum.getSerializeProtocol())).findFirst().orElse(new KryoSerializer());
}
}
@Configuration
static class RedisConfiguration {
private final Environment env;
@Autowired
public RedisConfiguration(Environment env) {
RedisConfiguration(final Environment env) {
this.env = env;
}
@Bean
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
@ -132,7 +114,6 @@ public class AdminConfiguration {
};
}
@Bean
@ConfigurationProperties(prefix = "tx.redis")
public JedisPoolConfig getRedisPoolConfig() {
@ -142,23 +123,19 @@ public class AdminConfiguration {
@Bean
@ConfigurationProperties(prefix = "tx.redis")
public JedisConnectionFactory getConnectionFactory() {
final Boolean cluster = env.getProperty("tx.redis.cluster", Boolean.class);
if (cluster) {
return new JedisConnectionFactory(getClusterConfiguration(),
getRedisPoolConfig());
return new JedisConnectionFactory(getClusterConfiguration(), getRedisPoolConfig());
} else {
return new JedisConnectionFactory(getRedisPoolConfig());
}
}
@Bean
@SuppressWarnings("unchecked")
public RedisTemplate redisTemplate() {
RedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(getConnectionFactory());
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();

View File

@ -38,6 +38,7 @@ import java.time.LocalDate;
import static com.google.common.collect.Lists.newArrayList;
/**
* SwaggerConfig.
* @author xiaoyu
*/
@Configuration
@ -58,11 +59,9 @@ public class SwaggerConfig {
.build();
}
// swagger
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
// .paths(paths())
.build().pathMapping("/").directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class).useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder().code(500).message("500 message")

View File

@ -33,17 +33,15 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
private final LoginService loginService;
@Autowired
public LoginController(LoginService loginService) {
public LoginController(final LoginService loginService) {
this.loginService = loginService;
}
@PostMapping("/login")
public AjaxResponse login(@RequestBody UserDTO userDTO) {
public AjaxResponse login(final @RequestBody UserDTO userDTO) {
final Boolean login = loginService.login(userDTO.getUserName(), userDTO.getPassword());
return AjaxResponse.success(login);
}

View File

@ -36,19 +36,13 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>Description: .</p>
* 事务恢复controller
*
* RecoverTransactionController.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/18 10:31
* @since JDK 1.8
*/
@RestController
@RequestMapping("/recover")
public class RecoverTransactionController {
private final RecoverTransactionService recoverTransactionService;
private final RecoverApplicationNameService recoverApplicationNameService;
@ -57,23 +51,23 @@ public class RecoverTransactionController {
private Integer recoverRetryMax;
@Autowired
public RecoverTransactionController(RecoverTransactionService recoverTransactionService, RecoverApplicationNameService recoverApplicationNameService) {
public RecoverTransactionController(final RecoverTransactionService recoverTransactionService,
final RecoverApplicationNameService recoverApplicationNameService) {
this.recoverTransactionService = recoverTransactionService;
this.recoverApplicationNameService = recoverApplicationNameService;
}
@Permission
@PostMapping(value = "/listPage")
public AjaxResponse listPage(@RequestBody RecoverTransactionQuery recoverQuery) {
public AjaxResponse listPage(final @RequestBody RecoverTransactionQuery recoverQuery) {
final CommonPager<TransactionRecoverVO> pager =
recoverTransactionService.listByPage(recoverQuery);
return AjaxResponse.success(pager);
}
@PostMapping(value = "/batchRemove")
@Permission
public AjaxResponse batchRemove(@RequestBody RecoverDTO recoverDTO) {
public AjaxResponse batchRemove(final @RequestBody RecoverDTO recoverDTO) {
final Boolean success = recoverTransactionService.batchRemove(recoverDTO.getIds(), recoverDTO.getApplicationName());
return AjaxResponse.success(success);
@ -82,7 +76,7 @@ public class RecoverTransactionController {
@PostMapping(value = "/update")
@Permission
public AjaxResponse update(@RequestBody RecoverDTO recoverDTO) {
public AjaxResponse update(final @RequestBody RecoverDTO recoverDTO) {
if (recoverRetryMax < recoverDTO.getRetry()) {
return AjaxResponse.error("重试次数超过最大设置,请您重新设置!");
}
@ -99,5 +93,4 @@ public class RecoverTransactionController {
return AjaxResponse.success(list);
}
}

View File

@ -33,30 +33,23 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>Description: .</p>
* 查询TxManager存储的事务item信息
*
* TxTransactionGroupController.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/18 10:31
* @since JDK 1.8
*/
@RestController
@RequestMapping("/tx")
public class TxTransactionGroupController {
private final TxTransactionGroupService txTransactionGroupService;
@Autowired
public TxTransactionGroupController(TxTransactionGroupService txTransactionGroupService) {
public TxTransactionGroupController(final TxTransactionGroupService txTransactionGroupService) {
this.txTransactionGroupService = txTransactionGroupService;
}
@Permission
@PostMapping(value = "/listPage")
public AjaxResponse listPage(@RequestBody TxTransactionQuery txTransactionQuery) {
public AjaxResponse listPage(final @RequestBody TxTransactionQuery txTransactionQuery) {
final CommonPager<TxTransactionGroupVO> commonPager =
txTransactionGroupService.listByPage(txTransactionQuery);
return AjaxResponse.success(commonPager);
@ -64,11 +57,8 @@ public class TxTransactionGroupController {
@Permission
@PostMapping(value = "/batchRemove")
public AjaxResponse batchRemove(@RequestBody List<String> txGroupIds) {
public AjaxResponse batchRemove(final @RequestBody List<String> txGroupIds) {
return AjaxResponse.success(txTransactionGroupService.batchRemove(txGroupIds));
}
}

View File

@ -24,17 +24,14 @@ import java.io.Serializable;
import java.util.List;
/**
* <p>Description: .</p>
*
* RecoverDTO.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/24 16:24
* @since JDK 1.8
*/
@Data
public class RecoverDTO implements Serializable {
private static final long serialVersionUID = 6905402148490426011L;
private String applicationName;
private List<String> ids;

View File

@ -23,17 +23,14 @@ import lombok.Data;
import java.io.Serializable;
/**
* <p>Description: .</p>
*
* UserDTO.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/23 18:18
* @since JDK 1.8
*/
@Data
public class UserDTO implements Serializable {
private static final long serialVersionUID = -3479973014221253748L;
private String userName;
private String password;

View File

@ -17,7 +17,6 @@
**
*/
package com.raincat.admin.filter;
import org.springframework.stereotype.Component;
@ -32,33 +31,26 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* <p>Description: .</p>
*
* CorsFilter.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/23 17:57
* @since JDK 1.8
*//*
*/
*/
@Component
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
public void init(final FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Request-Headers","content-type");
response.setHeader("Access-Control-Request-Headers", "content-type");
chain.doFilter(req, res);
}
@ -67,6 +59,5 @@ public class CorsFilter implements Filter {
}
}

View File

@ -27,16 +27,12 @@ import com.raincat.common.holder.DateUtils;
import com.raincat.common.netty.bean.TxTransactionItem;
/**
* <p>Description: .</p>
*
* ConvertHelper.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/23 11:53
* @since JDK 1.8
*/
public class ConvertHelper {
public static TransactionRecoverVO buildVO(TransactionRecoverAdapter adapter) {
public static TransactionRecoverVO buildVO(final TransactionRecoverAdapter adapter) {
TransactionRecoverVO vo = new TransactionRecoverVO();
vo.setId(adapter.getTransId());
vo.setCreateTime(DateUtils.parseDate(adapter.getCreateTime()));
@ -48,10 +44,9 @@ public class ConvertHelper {
vo.setTargetClass(adapter.getTargetClass());
vo.setTargetMethod(adapter.getTargetMethod());
return vo;
}
public static TxTransactionItemVO buildTxItemVO(TxTransactionItem item) {
public static TxTransactionItemVO buildTxItemVO(final TxTransactionItem item) {
TxTransactionItemVO vo = new TxTransactionItemVO();
vo.setCreateDate(item.getCreateDate());
vo.setModelName(item.getModelName());
@ -69,4 +64,5 @@ public class ConvertHelper {
vo.setMessage(item.getMessage());
return vo;
}
}

View File

@ -21,95 +21,61 @@ package com.raincat.admin.helper;
import com.raincat.admin.page.PageParameter;
/**
* <p>Description: .</p>
*
* PageHelper.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 18:30
* @since JDK 1.8
*/
public class PageHelper {
public static PageParameter buildPage(PageParameter pageParameter, int totalCount) {
public static PageParameter buildPage(final PageParameter pageParameter, final int totalCount) {
final int currentPage = pageParameter.getCurrentPage();
pageParameter.setTotalCount(totalCount);
int totalPage = totalCount / pageParameter.getPageSize() +
((totalCount % pageParameter.getPageSize() == 0) ? 0 : 1);
int totalPage = totalCount / pageParameter.getPageSize()
+ ((totalCount % pageParameter.getPageSize() == 0) ? 0 : 1);
pageParameter.setTotalPage(totalPage);
pageParameter.setPrePage(currentPage - 1);
pageParameter.setNextPage(currentPage + 1);
return pageParameter;
}
/**
* sqlserver的分页语句
* sqlserver的分页语句.
*
* @param sql
* @param page
* @param sql sql
* @param page page
* @return String
*/
public static StringBuilder buildPageSqlForSqlserver(String sql, PageParameter page) {
public static StringBuilder buildPageSqlForSqlserver(final String sql, final PageParameter page) {
StringBuilder pageSql = new StringBuilder(100);
String start = String.valueOf((page.getCurrentPage() - 1) * page.getPageSize());
pageSql.append(sql);
pageSql.append(" order by 1");
pageSql.append(" offset " + start + " rows fetch next " + page.getPageSize() + " rows only ");
pageSql.append(" offset ").append(start).append(" rows fetch next ").append(page.getPageSize()).append(" rows only ");
return pageSql;
}
/**
* sqlserver的分页语句
* mysql的分页语句.
*
* @param sql
* @param page
* @param sql sql
* @param page page
* @return String
*/
public static StringBuilder buildPageSqlForSqlserver(String sql, PageParameter page, String orderBy) {
public static StringBuilder buildPageSqlForMysql(final String sql, final PageParameter page) {
StringBuilder pageSql = new StringBuilder(100);
String start = String.valueOf((page.getCurrentPage() - 1) * page.getPageSize());
pageSql.append(sql);
pageSql.append(orderBy);
pageSql.append(" offset " + start + " rows fetch next " + page.getPageSize() + " rows only ");
pageSql.append(" limit ").append(start).append(",").append(page.getPageSize());
return pageSql;
}
/**
* mysql的分页语句
* 参考hibernate的实现完成oracle的分页.
*
* @param sql
* @param page
* @param sql sql
* @param page page
* @return String
*/
public static StringBuilder buildPageSqlForMysql(String sql, PageParameter page) {
StringBuilder pageSql = new StringBuilder(100);
String start = String.valueOf((page.getCurrentPage() - 1) * page.getPageSize());
pageSql.append(sql);
pageSql.append(" limit " + start + "," + page.getPageSize());
return pageSql;
}
/**
* mysql的分页语句
*
* @param sql
* @param page
* @return String
*/
public static StringBuilder buildPageSqlForMysql(String sql, PageParameter page, String orderBy) {
StringBuilder pageSql = new StringBuilder(100);
String start = String.valueOf((page.getCurrentPage() - 1) * page.getPageSize());
pageSql.append(sql);
pageSql.append(orderBy);
pageSql.append(" limit " + start + "," + page.getPageSize());
return pageSql;
}
/**
* 参考hibernate的实现完成oracle的分页
*
* @param sql
* @param page
* @return String
*/
public static StringBuilder buildPageSqlForOracle(String sql, PageParameter page) {
public static StringBuilder buildPageSqlForOracle(final String sql, final PageParameter page) {
StringBuilder pageSql = new StringBuilder(100);
String start = String.valueOf((page.getCurrentPage() - 1) * page.getPageSize());
String end = String.valueOf(page.getCurrentPage() * page.getPageSize());

View File

@ -29,19 +29,17 @@ import java.lang.reflect.Method;
import java.util.Objects;
/**
* <p>Description: .</p>
*
* AuthInterceptor.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/23 20:08
* @since JDK 1.8
*/
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
public boolean preHandle(final HttpServletRequest request,
final HttpServletResponse response,
final Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = ((HandlerMethod) handler);
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
final Permission annotation = method.getAnnotation(Permission.class);
if (Objects.isNull(annotation)) {
@ -50,8 +48,8 @@ public class AuthInterceptor extends HandlerInterceptorAdapter {
final boolean login = annotation.isLogin();
if (login) {
if (!LoginServiceImpl.LOGIN_SUCCESS) {
request.setAttribute("code","404");
request.setAttribute("msg", "请您先登录");
request.setAttribute("code", "404");
request.setAttribute("msg", "please login");
request.getRequestDispatcher("/").forward(request, response);
return Boolean.FALSE;
}
@ -60,5 +58,4 @@ public class AuthInterceptor extends HandlerInterceptorAdapter {
return super.preHandle(request, response, handler);
}
}

View File

@ -24,21 +24,21 @@ import java.io.Serializable;
import java.util.List;
/**
* CommonPager.
* @author xiaoyu
*/
@Data
public class CommonPager<T> implements Serializable {
private static final long serialVersionUID = -1220101004792874251L;
/**
* 分页信息
* page.
*/
private PageParameter page;
/**
* 返回数据
* dataList.
*/
private List<T> dataList;

View File

@ -23,38 +23,40 @@ import lombok.Data;
import java.io.Serializable;
/**
* <p>Description: .</p>
*
* PageParameter.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/18 15:51
* @since JDK 1.8
*/
@Data
public class PageParameter implements Serializable {
private static final long serialVersionUID = -8324693985921606090L;
public static final int DEFAULT_PAGE_SIZE = 10;
private static final long serialVersionUID = -8324693985921606090L;
private int pageSize;
private int currentPage;
private int prePage;
private int nextPage;
private int totalPage;
private int totalCount;
public PageParameter() {
this.currentPage = 1;
this.pageSize = DEFAULT_PAGE_SIZE;
}
/**
*
* @param currentPage 当前页
* @param pageSize 每页大小
*/
public PageParameter(int currentPage, int pageSize) {
public PageParameter(final int currentPage, final int pageSize) {
this.currentPage = currentPage;
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
}
}

View File

@ -24,12 +24,8 @@ import lombok.Data;
import java.io.Serializable;
/**
* <p>Description: .</p>
*
* RecoverTransactionQuery.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 16:46
* @since JDK 1.8
*/
@Data
public class RecoverTransactionQuery implements Serializable {
@ -37,25 +33,24 @@ public class RecoverTransactionQuery implements Serializable {
private static final long serialVersionUID = 3297929795348894462L;
/**
* 应用名称
* 应用名称.
*/
private String applicationName;
/**
* 事务组id
* 事务组id.
*/
private String txGroupId;
/**
* 重试次数
* 重试次数.
*/
private Integer retry;
/**
* 分页信息
* 分页信息.
*/
private PageParameter pageParameter;
}

View File

@ -24,17 +24,14 @@ import lombok.Data;
import java.io.Serializable;
/**
* <p>Description: .</p>
*
* TxTransactionQuery.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 16:46
* @since JDK 1.8
*/
@Data
public class TxTransactionQuery implements Serializable {
private static final long serialVersionUID = 1897647164293554953L;
private String txGroupId;
private String taskKey;

View File

@ -19,26 +19,22 @@
package com.raincat.admin.service;
/**
* <p>Description: .</p>
*
* LoginService.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/20 10:17
* @since JDK 1.8
*/
public interface LoginService {
/**
* 登录接口验证用户名 密码
* 登录接口验证用户名 密码.
* @param userName 用户名
* @param password 密码
* @return true 成功
*/
Boolean login(String userName,String password);
Boolean login(String userName, String password);
/**
* 用户登出
* 用户登出.
* @return true 成功
*/
Boolean logout();

View File

@ -21,20 +21,17 @@ package com.raincat.admin.service;
import java.util.List;
/**
* <p>Description: .</p>
* RecoverApplicationNameService.
*
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/20 16:34
* @since JDK 1.8
*/
public interface RecoverApplicationNameService {
/**
* 获取之前参与分布式事务项目的应用名称
* 获取之前参与分布式事务项目的应用名称.
*
* @return List<String>
* @return appName list.
*/
List<String> list();
}

View File

@ -25,27 +25,23 @@ import com.raincat.admin.vo.TransactionRecoverVO;
import java.util.List;
/**
* <p>Description: .</p>
*
* RecoverTransactionService.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 16:36
* @since JDK 1.8
*/
public interface RecoverTransactionService {
/**
* 分页获取补偿事务信息
* 分页获取补偿事务信息.
*
* @param query 查询条件
* @return CommonPager<TransactionRecoverVO>
* @return CommonPager TransactionRecoverVO
*/
CommonPager<TransactionRecoverVO> listByPage(RecoverTransactionQuery query);
/**
* 批量删除补偿事务信息
* 批量删除补偿事务信息.
*
* @param ids ids 事务id集合
* @param applicationName 应用名称
@ -55,7 +51,7 @@ public interface RecoverTransactionService {
/**
* 更改恢复次数
* 更改恢复次数.
*
* @param id 事务id
* @param retry 恢复次数

View File

@ -25,25 +25,21 @@ import com.raincat.admin.vo.TxTransactionGroupVO;
import java.util.List;
/**
* <p>Description: .</p>
*
* TxTransactionGroupService.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/18 15:38
* @since JDK 1.8
*/
public interface TxTransactionGroupService {
/**
* 分页获取事务组里面的事务信息
* 分页获取事务组里面的事务信息.
*
* @param txTransactionQuery 查询条件
* @return CommonPager<TxTransactionGroupVO>
* @return CommonPager TxTransactionGroupVO
*/
CommonPager<TxTransactionGroupVO> listByPage(TxTransactionQuery txTransactionQuery);
/**
* 批量删除事务信息
* 批量删除事务信息.
*
* @param txGroupIdList 事务组id集合
* @return true 成功

View File

@ -26,40 +26,27 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* <p>Description: .</p>
*
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/20 10:19
* @since JDK 1.8
* LoginServiceImpl.
* @author xiaoyu
*/
@Service("loginService")
public class LoginServiceImpl implements LoginService {
public static boolean LOGIN_SUCCESS = false;
/**
* logger
* logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(LoginServiceImpl.class);
@Value("${tx.admin.userName}")
private String userName;
@Value("${tx.admin.password}")
private String password;
public static boolean LOGIN_SUCCESS = false;
/**
* 登录接口验证用户名 密码
*
* @param userName 用户名
* @param password 密码
* @return true 成功
*/
@Override
public Boolean login(String userName, String password) {
public Boolean login(final String userName, final String password) {
LogUtil.info(LOGGER, "输入的用户名密码为:{}", () -> userName + "," + password);
if (userName.equals(this.userName) && password.equals(this.password)) {
LOGIN_SUCCESS = true;
@ -68,11 +55,6 @@ public class LoginServiceImpl implements LoginService {
return Boolean.FALSE;
}
/**
* 用户登出
*
* @return true 成功
*/
@Override
public Boolean logout() {
LOGIN_SUCCESS = false;

View File

@ -31,7 +31,6 @@ import com.raincat.common.holder.RepositoryPathUtils;
import com.raincat.common.serializer.ObjectSerializer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.File;
import java.io.FileInputStream;
@ -45,43 +44,29 @@ import java.util.Objects;
import java.util.stream.Collectors;
/**
* <p>Description: .</p>
* 文件实现
*
* file impl.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 17:08
* @since JDK 1.8
*/
public class FileRecoverTransactionServiceImpl implements RecoverTransactionService {
private final ObjectSerializer objectSerializer;
@Autowired
private ObjectSerializer objectSerializer;
public FileRecoverTransactionServiceImpl(final ObjectSerializer objectSerializer) {
this.objectSerializer=objectSerializer;
}
/**
* 分页获取补偿事务信息
*
* @param query 查询条件
* @return CommonPager<TransactionRecoverVO>
*/
@Override
public CommonPager<TransactionRecoverVO> listByPage(RecoverTransactionQuery query) {
public CommonPager<TransactionRecoverVO> listByPage(final RecoverTransactionQuery query) {
final String filePath = RepositoryPathUtils.buildFilePath(query.getApplicationName());
final PageParameter pageParameter = query.getPageParameter();
final int currentPage = pageParameter.getCurrentPage();
final int pageSize = pageParameter.getPageSize();
int start = (currentPage - 1) * pageSize;
CommonPager<TransactionRecoverVO> voCommonPager = new CommonPager<>();
File path;
File[] files;
int totalCount;
List<TransactionRecoverVO> voList;
//如果只查 重试条件的
if (StringUtils.isBlank(query.getTxGroupId()) && Objects.nonNull(query.getRetry())) {
path = new File(filePath);
@ -93,12 +78,15 @@ public class FileRecoverTransactionServiceImpl implements RecoverTransactionServ
.filter(vo -> vo.getRetriedCount() < query.getRetry())
.collect(Collectors.toList());
totalCount = collect.size();
voList = collect.stream().skip(start).limit(pageSize).collect(Collectors.toList());
voList = collect.stream()
.skip(start)
.limit(pageSize).collect(Collectors.toList());
} else {
totalCount = 0;
voList = null;
}
} else if (StringUtils.isNoneBlank(query.getTxGroupId()) && Objects.isNull(query.getRetry())) {
} else if (StringUtils.isNoneBlank(query.getTxGroupId())
&& Objects.isNull(query.getRetry())) {
final String fullFileName = getFullFileName(filePath, query.getTxGroupId());
final File file = new File(fullFileName);
files = new File[]{file};
@ -116,7 +104,7 @@ public class FileRecoverTransactionServiceImpl implements RecoverTransactionServ
} else {
path = new File(filePath);
files = path.listFiles();
totalCount = files.length;
totalCount = Objects.requireNonNull(files).length;
voList = findByPage(files, start, pageSize);
}
voCommonPager.setPage(PageHelper.buildPage(query.getPageParameter(), totalCount));
@ -124,38 +112,22 @@ public class FileRecoverTransactionServiceImpl implements RecoverTransactionServ
return voCommonPager;
}
/**
* 批量删除补偿事务信息
*
* @param ids ids 事务id集合
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean batchRemove(List<String> ids, String applicationName) {
public Boolean batchRemove(final List<String> ids, final String applicationName) {
if (CollectionUtils.isEmpty(ids) || StringUtils.isBlank(applicationName)) {
return Boolean.FALSE;
}
final String filePath = RepositoryPathUtils.buildFilePath(applicationName);
ids.stream().map(id -> new File(getFullFileName(filePath, id)))
.forEach(File::delete);
ids.stream().map(id ->
new File(getFullFileName(filePath, id))).forEach(File::delete);
return Boolean.TRUE;
}
/**
* 更改恢复次数
*
* @param id 事务id
* @param retry 恢复次数
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean updateRetry(String id, Integer retry, String applicationName) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(applicationName) || Objects.isNull(retry)) {
public Boolean updateRetry(final String id, final Integer retry, final String applicationName) {
if (StringUtils.isBlank(id)
|| StringUtils.isBlank(applicationName)
|| Objects.isNull(retry)) {
return false;
}
final String filePath = RepositoryPathUtils.buildFilePath(applicationName);
@ -172,14 +144,10 @@ public class FileRecoverTransactionServiceImpl implements RecoverTransactionServ
writeFile(adapter, fullFileName);
return true;
}
return false;
}
private void writeFile(TransactionRecoverAdapter adapter, String fullFileName) {
private void writeFile(final TransactionRecoverAdapter adapter, final String fullFileName) {
try {
RandomAccessFile raf = new RandomAccessFile(fullFileName, "rw");
try (FileChannel channel = raf.getChannel()) {
@ -197,30 +165,24 @@ public class FileRecoverTransactionServiceImpl implements RecoverTransactionServ
}
}
private TransactionRecoverAdapter readRecover(File file) {
private TransactionRecoverAdapter readRecover(final File file) {
try {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] content = new byte[(int) file.length()];
final int read = fis.read(content);
fis.read(content);
return objectSerializer.deSerialize(content, TransactionRecoverAdapter.class);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private TransactionRecoverVO readTransaction(File file) {
private TransactionRecoverVO readTransaction(final File file) {
try {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] content = new byte[(int) file.length()];
final int read = fis.read(content);
fis.read(content);
final TransactionRecoverAdapter adapter = objectSerializer.deSerialize(content, TransactionRecoverAdapter.class);
return ConvertHelper.buildVO(adapter);
}
@ -230,7 +192,7 @@ public class FileRecoverTransactionServiceImpl implements RecoverTransactionServ
}
}
private List<TransactionRecoverVO> findAll(File[] files) {
private List<TransactionRecoverVO> findAll(final File[] files) {
if (files != null && files.length > 0) {
return Arrays.stream(files)
.map(this::readTransaction)
@ -239,7 +201,7 @@ public class FileRecoverTransactionServiceImpl implements RecoverTransactionServ
return null;
}
private List<TransactionRecoverVO> findByPage(File[] files, int start, int pageSize) {
private List<TransactionRecoverVO> findByPage(final File[] files, final int start, final int pageSize) {
if (files != null && files.length > 0) {
return Arrays.stream(files).skip(start).limit(pageSize)
.map(this::readTransaction)
@ -248,9 +210,8 @@ public class FileRecoverTransactionServiceImpl implements RecoverTransactionServ
return null;
}
private String getFullFileName(String filePath, String id) {
private String getFullFileName(final String filePath, final String id) {
return String.format("%s/%s", filePath, id);
}
}

View File

@ -38,13 +38,8 @@ import java.util.Objects;
import java.util.stream.Collectors;
/**
* <p>Description: .</p>
* jdbc实现
*
* jdbc impl.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 17:08
* @since JDK 1.8
*/
public class JdbcRecoverTransactionServiceImpl implements RecoverTransactionService {
@ -53,64 +48,35 @@ public class JdbcRecoverTransactionServiceImpl implements RecoverTransactionServ
private String dbType;
/**
* 分页获取补偿事务信息
*
* @param query 查询条件
* @return CommonPager<TransactionRecoverVO>
*/
@Override
public CommonPager<TransactionRecoverVO> listByPage(RecoverTransactionQuery query) {
public CommonPager<TransactionRecoverVO> listByPage(final RecoverTransactionQuery query) {
final String tableName = RepositoryPathUtils.buildDbTableName(query.getApplicationName());
final PageParameter pageParameter = query.getPageParameter();
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("select id,target_class,target_method," +
" retried_count,create_time,last_time,version,group_id,task_id from ")
sqlBuilder.append("select id,target_class,target_method,"
+ " retried_count,create_time,last_time,version,group_id,task_id from ")
.append(tableName).append(" where 1= 1 ");
if (StringUtils.isNoneBlank(query.getTxGroupId())) {
sqlBuilder.append(" and group_id = ").append(query.getTxGroupId());
}
if (Objects.nonNull(query.getRetry())) {
sqlBuilder.append(" and retried_count < ").append(query.getRetry());
}
final String sql = buildPageSql(sqlBuilder.toString(), pageParameter);
CommonPager<TransactionRecoverVO> pager = new CommonPager<>();
final List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
if (CollectionUtils.isNotEmpty(mapList)) {
pager.setDataList(mapList.stream().map(this::buildByMap).collect(Collectors.toList()));
pager.setDataList(mapList.stream()
.map(this::buildByMap).collect(Collectors.toList()));
}
final Integer totalCount =
jdbcTemplate.queryForObject("select count(1) from " + tableName, Integer.class);
jdbcTemplate.queryForObject(String.format("select count(1) from %s", tableName), Integer.class);
pager.setPage(PageHelper.buildPage(pageParameter, totalCount));
return pager;
}
/**
* 批量删除补偿事务信息
*
* @param ids ids 事务id集合
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean batchRemove(List<String> ids, String applicationName) {
public Boolean batchRemove(final List<String> ids, final String applicationName) {
if (CollectionUtils.isEmpty(ids) || StringUtils.isBlank(applicationName)) {
return Boolean.FALSE;
}
@ -118,39 +84,25 @@ public class JdbcRecoverTransactionServiceImpl implements RecoverTransactionServ
ids.stream()
.map(id -> buildDelSql(tableName, id))
.forEach(sql -> jdbcTemplate.execute(sql));
return Boolean.TRUE;
}
/**
* 更改恢复次数
*
* @param id 事务id
* @param retry 恢复次数
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean updateRetry(String id, Integer retry, String applicationName) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(applicationName) || Objects.isNull(retry)) {
public Boolean updateRetry(final String id, final Integer retry, final String applicationName) {
if (StringUtils.isBlank(id)
|| StringUtils.isBlank(applicationName)
|| Objects.isNull(retry)) {
return false;
}
final String tableName = RepositoryPathUtils.buildDbTableName(applicationName);
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("update ").append(tableName)
.append(" set retried_count = ")
.append(retry).append(",last_time= '")
.append(DateUtils.getCurrentDateTime()).append("'")
.append(" where id =").append(id);
jdbcTemplate.execute(sqlBuilder.toString());
String sqlBuilder =
String.format("update %s set retried_count = \n%d,last_time= '%s' where id =%s",
tableName, retry, DateUtils.getCurrentDateTime(), id);
jdbcTemplate.execute(sqlBuilder);
return Boolean.TRUE;
}
private TransactionRecoverVO buildByMap(Map<String, Object> map) {
private TransactionRecoverVO buildByMap(final Map<String, Object> map) {
TransactionRecoverVO vo = new TransactionRecoverVO();
vo.setId((String) map.get("id"));
vo.setRetriedCount((Integer) map.get("retried_count"));
@ -164,7 +116,7 @@ public class JdbcRecoverTransactionServiceImpl implements RecoverTransactionServ
return vo;
}
private String buildPageSql(String sql, PageParameter pageParameter) {
private String buildPageSql(final String sql, final PageParameter pageParameter) {
switch (dbType) {
case "mysql":
return PageHelper.buildPageSqlForMysql(sql, pageParameter).toString();
@ -175,19 +127,13 @@ public class JdbcRecoverTransactionServiceImpl implements RecoverTransactionServ
default:
return null;
}
}
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
public void setDbType(final String dbType) {
this.dbType = DbTypeUtils.buildByDriverClassName(dbType);
}
private String buildDelSql(String tableName, String id) {
private String buildDelSql(final String tableName, final String id) {
return "DELETE FROM " + tableName + " WHERE ID=" + id;
}
}

View File

@ -42,64 +42,40 @@ import java.util.Objects;
import java.util.stream.Collectors;
/**
* <p>Description: .</p>
* Mongodb 实现
*
* Mongodb impl.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 17:08
* @since JDK 1.8
*/
public class MongoRecoverTransactionServiceImpl implements RecoverTransactionService {
private MongoTemplate mongoTemplate;
public MongoRecoverTransactionServiceImpl(MongoTemplate mongoTemplate) {
public MongoRecoverTransactionServiceImpl(final MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
/**
* 分页获取补偿事务信息
*
* @param query 查询条件
* @return CommonPager<TransactionRecoverVO>
*/
@Override
public CommonPager<TransactionRecoverVO> listByPage(RecoverTransactionQuery query) {
public CommonPager<TransactionRecoverVO> listByPage(final RecoverTransactionQuery query) {
CommonPager<TransactionRecoverVO> voCommonPager = new CommonPager<>();
final String mongoTableName = RepositoryPathUtils.buildMongoTableName(query.getApplicationName());
final PageParameter pageParameter = query.getPageParameter();
final int currentPage = pageParameter.getCurrentPage();
final int pageSize = pageParameter.getPageSize();
int start = (currentPage - 1) * pageSize;
Query baseQuery = new Query();
if (StringUtils.isNoneBlank(query.getTxGroupId())) {
baseQuery.addCriteria(new Criteria("groupId").is(query.getTxGroupId()));
}
if (Objects.nonNull(query.getRetry())) {
baseQuery.addCriteria(new Criteria("retriedCount").lt(query.getRetry()));
}
final long totalCount = mongoTemplate.count(baseQuery, mongoTableName);
if (totalCount <= 0) {
return voCommonPager;
}
int start = (currentPage - 1) * pageSize;
voCommonPager.setPage(PageHelper.buildPage(query.getPageParameter(), (int) totalCount));
baseQuery.skip(start).limit(pageSize);
final List<MongoAdapter> mongoAdapters =
mongoTemplate.find(baseQuery, MongoAdapter.class, mongoTableName);
if (CollectionUtils.isNotEmpty(mongoAdapters)) {
final List<TransactionRecoverVO> recoverVOS =
mongoAdapters
@ -108,24 +84,15 @@ public class MongoRecoverTransactionServiceImpl implements RecoverTransactionSer
.collect(Collectors.toList());
voCommonPager.setDataList(recoverVOS);
}
return voCommonPager;
}
/**
* 批量删除补偿事务信息
*
* @param ids ids 事务id集合
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean batchRemove(List<String> ids, String applicationName) {
public Boolean batchRemove(final List<String> ids, final String applicationName) {
if (CollectionUtils.isEmpty(ids) || StringUtils.isBlank(applicationName)) {
return Boolean.FALSE;
}
final String mongoTableName = RepositoryPathUtils.buildMongoTableName(applicationName);
ids.forEach(id -> {
Query query = new Query();
query.addCriteria(new Criteria("transId").is(id));
@ -135,17 +102,11 @@ public class MongoRecoverTransactionServiceImpl implements RecoverTransactionSer
return Boolean.TRUE;
}
/**
* 更改恢复次数
*
* @param id 事务id
* @param retry 恢复次数
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean updateRetry(String id, Integer retry, String applicationName) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(applicationName) || Objects.isNull(retry)) {
public Boolean updateRetry(final String id, final Integer retry, final String applicationName) {
if (StringUtils.isBlank(id)
|| StringUtils.isBlank(applicationName)
|| Objects.isNull(retry)) {
return Boolean.FALSE;
}
final String mongoTableName = RepositoryPathUtils.buildMongoTableName(applicationName);
@ -163,5 +124,4 @@ public class MongoRecoverTransactionServiceImpl implements RecoverTransactionSer
return Boolean.TRUE;
}
}

View File

@ -26,25 +26,15 @@ import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>Description: .</p>
*
* RecoverApplicationNameServiceImpl.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/20 16:39
* @since JDK 1.8
*/
@Service("recoverApplicationNameService")
public class RecoverApplicationNameServiceImpl implements RecoverApplicationNameService {
@Value("${recover.application.list}")
private String appNameList;
/**
* 获取之前参与分布式事务项目的应用名称
*
* @return List<String>
*/
@Override
public List<String> list() {
return Splitter.on(",").splitToList(appNameList);

View File

@ -41,57 +41,31 @@ import java.util.Set;
import java.util.stream.Collectors;
/**
* <p>Description: .</p>
* redis实现
*
* redis impl.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 17:08
* @since JDK 1.8
*/
@SuppressWarnings("unchecked")
public class RedisRecoverTransactionServiceImpl implements RecoverTransactionService {
private ObjectSerializer objectSerializer;
private JedisClient jedisClient;
public RedisRecoverTransactionServiceImpl(JedisClient jedisClient) {
public RedisRecoverTransactionServiceImpl(final JedisClient jedisClient, final ObjectSerializer objectSerializer) {
this.jedisClient = jedisClient;
this.objectSerializer = objectSerializer;
}
@Autowired
private ObjectSerializer objectSerializer;
/**
* 分页获取补偿事务信息
*
* @param query 查询条件
* @return CommonPager<TransactionRecoverVO>
*/
@Override
public CommonPager<TransactionRecoverVO> listByPage(RecoverTransactionQuery query) {
public CommonPager<TransactionRecoverVO> listByPage(final RecoverTransactionQuery query) {
CommonPager<TransactionRecoverVO> commonPager = new CommonPager<>();
final String redisKey = RepositoryPathUtils.buildRedisKey(query.getApplicationName());
final int currentPage = query.getPageParameter().getCurrentPage();
final int pageSize = query.getPageParameter().getPageSize();
int start = (currentPage - 1) * pageSize;
//transaction:recover:alipay-service:
//获取所有的key
Set<byte[]> keys;
List<TransactionRecoverVO> voList;
int totalCount;
//如果只查 重试条件的
if (StringUtils.isBlank(query.getTxGroupId()) && Objects.nonNull(query.getRetry())) {
keys = jedisClient.keys((redisKey + "*").getBytes());
final List<TransactionRecoverVO> all = findAll(keys);
@ -129,23 +103,25 @@ public class RedisRecoverTransactionServiceImpl implements RecoverTransactionSer
return commonPager;
}
private List<TransactionRecoverVO> findAll(Set<byte[]> keys) {
private List<TransactionRecoverVO> findAll(final Set<byte[]> keys) {
return keys.parallelStream()
.map(this::buildVOByKey).filter(Objects::nonNull).collect(Collectors.toList());
.map(this::buildVOByKey)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private List<TransactionRecoverVO> findByPage(Set<byte[]> keys, int start, int pageSize) {
return keys.parallelStream().skip(start).limit(pageSize)
.map(this::buildVOByKey).filter(Objects::nonNull).collect(Collectors.toList());
private List<TransactionRecoverVO> findByPage(final Set<byte[]> keys, final int start, final int pageSize) {
return keys.parallelStream()
.skip(start).limit(pageSize)
.map(this::buildVOByKey)
.filter(Objects::nonNull).collect(Collectors.toList());
}
private TransactionRecoverVO buildVOByKey(byte[] key) {
private TransactionRecoverVO buildVOByKey(final byte[] key) {
final byte[] bytes = jedisClient.get(key);
try {
final TransactionRecoverAdapter adapter = objectSerializer.deSerialize(bytes, TransactionRecoverAdapter.class);
final TransactionRecoverAdapter adapter =
objectSerializer.deSerialize(bytes, TransactionRecoverAdapter.class);
return ConvertHelper.buildVO(adapter);
} catch (TransactionException e) {
e.printStackTrace();
@ -153,36 +129,20 @@ public class RedisRecoverTransactionServiceImpl implements RecoverTransactionSer
}
}
/**
* 批量删除补偿事务信息
*
* @param ids ids 事务id集合
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean batchRemove(List<String> ids, String applicationName) {
public Boolean batchRemove(final List<String> ids, final String applicationName) {
if (CollectionUtils.isEmpty(ids) || StringUtils.isBlank(applicationName)) {
return Boolean.FALSE;
}
String keyPrefix = RepositoryPathUtils.buildRedisKey(applicationName);
final String[] keys = ids.stream()
.map(id -> cacheKey(keyPrefix, id)).toArray(String[]::new);
jedisClient.del(keys);
return Boolean.TRUE;
}
/**
* 更改恢复次数
*
* @param id 事务id
* @param retry 恢复次数
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean updateRetry(String id, Integer retry, String applicationName) {
public Boolean updateRetry(final String id, final Integer retry, final String applicationName) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(applicationName) || Objects.isNull(retry)) {
return Boolean.FALSE;
}
@ -203,7 +163,7 @@ public class RedisRecoverTransactionServiceImpl implements RecoverTransactionSer
}
private String cacheKey(String keyPrefix, String id) {
private String cacheKey(final String keyPrefix, final String id) {
return String.join(":", keyPrefix, id);
}

View File

@ -37,58 +37,36 @@ import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* <p>Description: .</p>
* zookeeper实现
*
* zookeeper impl.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 17:08
* @since JDK 1.8
*/
public class ZookeeperRecoverTransactionServiceImpl implements RecoverTransactionService {
private final ZooKeeper zooKeeper;
private ZooKeeper zooKeeper;
private final ObjectSerializer objectSerializer;
@Autowired
private ObjectSerializer objectSerializer;
public ZookeeperRecoverTransactionServiceImpl(ZooKeeper zooKeeper) {
public ZookeeperRecoverTransactionServiceImpl(final ZooKeeper zooKeeper, final ObjectSerializer objectSerializer) {
this.zooKeeper = zooKeeper;
this.objectSerializer = objectSerializer;
}
/**
* 分页获取补偿事务信息
*
* @param query 查询条件
* @return CommonPager<TransactionRecoverVO>
*/
@Override
public CommonPager<TransactionRecoverVO> listByPage(RecoverTransactionQuery query) {
public CommonPager<TransactionRecoverVO> listByPage(final RecoverTransactionQuery query) {
CommonPager<TransactionRecoverVO> voCommonPager = new CommonPager<>();
final int currentPage = query.getPageParameter().getCurrentPage();
final int pageSize = query.getPageParameter().getPageSize();
int start = (currentPage - 1) * pageSize;
final String rootPath = RepositoryPathUtils.buildZookeeperPath(query.getApplicationName());
List<String> zNodePaths;
List<TransactionRecoverVO> voList;
int totalCount;
try {
//如果只查 重试条件的
if (StringUtils.isBlank(query.getTxGroupId()) && Objects.nonNull(query.getRetry())) {
@ -126,51 +104,31 @@ public class ZookeeperRecoverTransactionServiceImpl implements RecoverTransactio
return voCommonPager;
}
/**
* 批量删除补偿事务信息
*
* @param ids ids 事务id集合
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean batchRemove(List<String> ids, String applicationName) {
public Boolean batchRemove(final List<String> ids, final String applicationName) {
if (CollectionUtils.isEmpty(ids) || StringUtils.isBlank(applicationName)) {
return Boolean.FALSE;
}
final String rootPath = RepositoryPathUtils.buildZookeeperPath(applicationName);
ids.stream().map(id -> {
try {
final String path = buildRootPath(rootPath, id);
byte[] content = zooKeeper.getData(path,
false, new Stat());
final TransactionRecoverAdapter adapter = objectSerializer.deSerialize(content, TransactionRecoverAdapter.class);
final TransactionRecoverAdapter adapter =
objectSerializer.deSerialize(content, TransactionRecoverAdapter.class);
zooKeeper.delete(path, adapter.getVersion());
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}).count();
return Boolean.TRUE;
}
/**
* 更改恢复次数
*
* @param id 事务id
* @param retry 恢复次数
* @param applicationName 应用名称
* @return true 成功
*/
@Override
public Boolean updateRetry(String id, Integer retry, String applicationName) {
public Boolean updateRetry(final String id, final Integer retry, final String applicationName) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(applicationName) || Objects.isNull(retry)) {
return Boolean.FALSE;
}
@ -179,7 +137,8 @@ public class ZookeeperRecoverTransactionServiceImpl implements RecoverTransactio
try {
byte[] content = zooKeeper.getData(path,
false, new Stat());
final TransactionRecoverAdapter adapter = objectSerializer.deSerialize(content, TransactionRecoverAdapter.class);
final TransactionRecoverAdapter adapter =
objectSerializer.deSerialize(content, TransactionRecoverAdapter.class);
adapter.setLastTime(DateUtils.getDateYYYY());
adapter.setRetriedCount(retry);
zooKeeper.create(path,
@ -189,38 +148,41 @@ public class ZookeeperRecoverTransactionServiceImpl implements RecoverTransactio
} catch (Exception e) {
e.printStackTrace();
}
return Boolean.FALSE;
}
private String buildRootPath(String rootPath, String id) {
private String buildRootPath(final String rootPath, final String id) {
return String.join("/", rootPath, id);
}
private List<TransactionRecoverVO> findAll(List<String> zNodePaths, String rootPath) {
private List<TransactionRecoverVO> findAll(final List<String> zNodePaths, final String rootPath) {
return zNodePaths.stream()
.filter(StringUtils::isNoneBlank)
.map(zNodePath -> buildByNodePath(rootPath, zNodePath)).collect(Collectors.toList());
.map(zNodePath -> buildByNodePath(rootPath, zNodePath))
.collect(Collectors.toList());
}
private List<TransactionRecoverVO> findByPage(List<String> zNodePaths, String rootPath, int start, int pageSize) {
private List<TransactionRecoverVO> findByPage(final List<String> zNodePaths,
final String rootPath,
final int start,
final int pageSize) {
return zNodePaths.stream().skip(start).limit(pageSize)
.filter(StringUtils::isNoneBlank)
.map(zNodePath -> buildByNodePath(rootPath, zNodePath)).collect(Collectors.toList());
.map(zNodePath -> buildByNodePath(rootPath, zNodePath))
.collect(Collectors.toList());
}
private TransactionRecoverVO buildByNodePath(String rootPath, String zNodePath) {
private TransactionRecoverVO buildByNodePath(final String rootPath, final String zNodePath) {
try {
byte[] content = zooKeeper.getData(buildRootPath(rootPath, zNodePath),
false, new Stat());
final TransactionRecoverAdapter adapter =
objectSerializer.deSerialize(content, TransactionRecoverAdapter.class);
return ConvertHelper.buildVO(adapter);
} catch (KeeperException | InterruptedException | TransactionException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -43,13 +43,8 @@ import java.util.Set;
import java.util.stream.Collectors;
/**
* <p>Description: .</p>
* redis实现用了redis sortSet来进行分页
*
* redis实现用了redis sortSet来进行分页.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/18 15:58
* @since JDK 1.8
*/
@Service("txTransactionItemService")
@SuppressWarnings("unchecked")
@ -58,29 +53,21 @@ public class RedisTxTransactionGroupServiceImpl implements TxTransactionGroupSer
private final RedisTemplate redisTemplate;
@Autowired
public RedisTxTransactionGroupServiceImpl(RedisTemplate redisTemplate) {
public RedisTxTransactionGroupServiceImpl(final RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public CommonPager<TxTransactionGroupVO> listByPage(TxTransactionQuery txTransactionQuery) {
public CommonPager<TxTransactionGroupVO> listByPage(final TxTransactionQuery txTransactionQuery) {
CommonPager<TxTransactionGroupVO> commonPager = new CommonPager<>();
final int currentPage = txTransactionQuery.getPageParameter().getCurrentPage();
final int pageSize = txTransactionQuery.getPageParameter().getPageSize();
int start = (currentPage - 1) * pageSize;
int end = currentPage * pageSize;
Set<String> keys;
Set<String> rangeKeys;
if (StringUtils.isNoneBlank(txTransactionQuery.getTxGroupId())) {
keys = Sets.newHashSet(String.format(CommonConstant.REDIS_PRE_FIX, txTransactionQuery.getTxGroupId()));
rangeKeys = Sets.newHashSet(txTransactionQuery.getTxGroupId());
} else {
keys = redisTemplate.keys(CommonConstant.REDIS_KEYS);
@ -92,9 +79,7 @@ public class RedisTxTransactionGroupServiceImpl implements TxTransactionGroupSer
return commonPager;
}
final int totalCount = keys.size();
commonPager.setPage(PageHelper.buildPage(txTransactionQuery.getPageParameter(), totalCount));
final List<TxTransactionGroupVO> groupVOS = rangeKeys.stream().map((String key) -> {
final Map<Object, TxTransactionItem> entries = redisTemplate.opsForHash()
.entries(String.format(CommonConstant.REDIS_PRE_FIX, key));
@ -123,19 +108,12 @@ public class RedisTxTransactionGroupServiceImpl implements TxTransactionGroupSer
return groupVO;
}).collect(Collectors.toList());
commonPager.setDataList(groupVOS);
return commonPager;
}
/**
* 批量删除事务信息
*
* @param txGroupIdList 事务组id集合
* @return true 成功
*/
@Override
public Boolean batchRemove(List<String> txGroupIdList) {
public Boolean batchRemove(final List<String> txGroupIdList) {
if (CollectionUtils.isEmpty(txGroupIdList)) {
return false;
}
@ -151,9 +129,6 @@ public class RedisTxTransactionGroupServiceImpl implements TxTransactionGroupSer
e.printStackTrace();
return false;
}
}
}

View File

@ -20,6 +20,8 @@ package com.raincat.admin.spi;
import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.base.Splitter;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.raincat.admin.service.RecoverTransactionService;
import com.raincat.admin.service.recover.FileRecoverTransactionServiceImpl;
import com.raincat.admin.service.recover.JdbcRecoverTransactionServiceImpl;
@ -29,8 +31,7 @@ import com.raincat.admin.service.recover.ZookeeperRecoverTransactionServiceImpl;
import com.raincat.common.jedis.JedisClient;
import com.raincat.common.jedis.JedisClientCluster;
import com.raincat.common.jedis.JedisClientSingle;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.raincat.common.serializer.ObjectSerializer;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
@ -56,13 +57,14 @@ import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
/**
* RecoverConfiguration.
* @author xiaoyu
*/
@Configuration
public class RecoverConfiguration {
/**
* spring.profiles.active = {}
* spring.profiles.active = {}.
*/
@Configuration
@Profile("db")
@ -71,7 +73,7 @@ public class RecoverConfiguration {
private final Environment env;
@Autowired
public JdbcRecoverConfiguration(Environment env) {
JdbcRecoverConfiguration(final Environment env) {
this.env = env;
}
@ -103,19 +105,20 @@ public class RecoverConfiguration {
return jdbcTransactionRecoverService;
}
}
@Configuration
@Profile("redis")
static class RedisRecoverConfiguration {
private final Environment env;
private final ObjectSerializer objectSerializer;
@Autowired
public RedisRecoverConfiguration(Environment env) {
RedisRecoverConfiguration(final Environment env, final ObjectSerializer objectSerializer) {
this.env = env;
this.objectSerializer = objectSerializer;
}
@Bean
@ -147,21 +150,26 @@ public class RecoverConfiguration {
jedisClient = new JedisClientSingle(jedisPool);
}
return new RedisRecoverTransactionServiceImpl(jedisClient);
return new RedisRecoverTransactionServiceImpl(jedisClient, objectSerializer);
}
}
@Configuration
@Profile("file")
static class FileRecoverConfiguration {
private final ObjectSerializer objectSerializer;
@Autowired
FileRecoverConfiguration(final ObjectSerializer objectSerializer) {
this.objectSerializer = objectSerializer;
}
@Bean
@Qualifier("fileTransactionRecoverService")
public RecoverTransactionService fileTransactionRecoverService() {
return new FileRecoverTransactionServiceImpl();
return new FileRecoverTransactionServiceImpl(objectSerializer);
}
}
@ -170,15 +178,17 @@ public class RecoverConfiguration {
@Profile("zookeeper")
static class ZookeeperRecoverConfiguration {
private final Environment env;
@Autowired
public ZookeeperRecoverConfiguration(Environment env) {
this.env = env;
}
private static final Lock LOCK = new ReentrantLock();
private final Environment env;
private final ObjectSerializer objectSerializer;
@Autowired
ZookeeperRecoverConfiguration(final Environment env, final ObjectSerializer objectSerializer) {
this.env = env;
this.objectSerializer = objectSerializer;
}
@Bean
@Qualifier("zookeeperTransactionRecoverService")
@ -198,7 +208,7 @@ public class RecoverConfiguration {
e.printStackTrace();
}
return new ZookeeperRecoverTransactionServiceImpl(zooKeeper);
return new ZookeeperRecoverTransactionServiceImpl(zooKeeper, objectSerializer);
}
}
@ -210,22 +220,19 @@ public class RecoverConfiguration {
private final Environment env;
@Autowired
public MongoRecoverConfiguration(Environment env) {
MongoRecoverConfiguration(final Environment env) {
this.env = env;
}
@Bean
@Qualifier("mongoTransactionRecoverService")
public RecoverTransactionService mongoTransactionRecoverService() {
MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
MongoCredential credential = MongoCredential.createScramSha1Credential(
env.getProperty("recover.mongo.userName"),
env.getProperty("recover.mongo.dbName"),
env.getProperty("recover.mongo.password").toCharArray());
clientFactoryBean.setCredentials(new MongoCredential[]{
credential
});
clientFactoryBean.setCredentials(new MongoCredential[]{credential});
List<String> urls = Splitter.on(",").trimResults().splitToList(env.getProperty("recover.mongo.url"));
ServerAddress[] sds = new ServerAddress[urls.size()];
for (int i = 0; i < sds.length; i++) {
@ -234,18 +241,17 @@ public class RecoverConfiguration {
sds[i] = new ServerAddress(address);
}
clientFactoryBean.setReplicaSetSeeds(sds);
MongoTemplate mongoTemplate = null;
try {
clientFactoryBean.afterPropertiesSet();
mongoTemplate = new MongoTemplate(clientFactoryBean.getObject(), env.getProperty("recover.mongo.dbName"));
mongoTemplate =
new MongoTemplate(clientFactoryBean.getObject(),
env.getProperty("recover.mongo.dbName"));
} catch (Exception e) {
e.printStackTrace();
}
return new MongoRecoverTransactionServiceImpl(mongoTemplate);
}
}
}

View File

@ -23,59 +23,53 @@ import lombok.Data;
import java.io.Serializable;
/**
* <p>Description: .</p>
*
* TransactionRecoverVO.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/19 16:37
* @since JDK 1.8
*/
@Data
public class TransactionRecoverVO implements Serializable {
private static final long serialVersionUID = 564418979137349581L;
private String id;
/**
* 重试次数
* 重试次数.
*/
private Integer retriedCount;
/**
* 创建时间
* 创建时间.
*/
private String createTime;
/**
* 创建时间
* 创建时间.
*/
private String lastTime;
/**
* 版本控制 防止并发问题
* 版本控制 防止并发问题.
*/
private Integer version;
/**
* 事务组id
* 事务组id.
*/
private String groupId;
/**
* 任务id
* 任务id.
*/
private String taskId;
/**
* 执行类名称
* 执行类名称.
*/
private String targetClass;
/**
* 执行方法
* 执行方法.
*/
private String targetMethod;

View File

@ -24,53 +24,51 @@ import java.io.Serializable;
import java.util.List;
/**
* <p>Description: .</p>
* TxTransactionGroupVO
* TxTransactionGroupVO.
* @author xiaoyu(Myth)
* @version 1.0
* @date 2017/10/25 10:12
* @since JDK 1.8
*/
@Data
public class TxTransactionGroupVO implements Serializable {
private static final long serialVersionUID = -7648437787462449972L;
/**
* 事务组id
* 事务组id.
*/
private String id;
/**
* 事务组状态
* 事务组状态.
*/
private String status;
/**
* 角色
* 角色.
*/
private String role;
/**
* 创建时间
* 创建时间.
*/
private String createDate;
/**
* 执行类名称
* 执行类名称.
*/
private String targetClass;
/**
* 执行方法
* 执行方法.
*/
private String targetMethod;
/**
* 耗时
* 耗时 .
*/
private Long consumeTime;
/**
* 事务项集合
* 事务项集合.
*/
private List<TxTransactionItemVO> itemVOList;

View File

@ -15,6 +15,7 @@
* along with this distribution; if not, see <http://www.gnu.org/licenses/>.
*
*/
package com.raincat.admin.vo;
import com.raincat.common.enums.TransactionRoleEnum;
@ -23,79 +24,75 @@ import lombok.Data;
import java.io.Serializable;
/**
* TxTransactionItemVO.
* @author xiaoyu
*/
@Data
public class TxTransactionItemVO implements Serializable {
private static final long serialVersionUID = 7873174484499376766L;
/**
* taskKey
* taskKey.
*/
private String taskKey;
/**
* 参与事务id
* 参与事务id.
*/
private String transId;
/**
* 事务状态 {@linkplain TransactionStatusEnum}
* 事务状态. {@linkplain TransactionStatusEnum}
*/
private String status;
/**
* 事务角色 {@linkplain TransactionRoleEnum}
* 事务角色. {@linkplain TransactionRoleEnum}
*/
private String role;
/**
* 模块信息
* 模块信息.
*/
private String modelName;
/**
* tm 的域名信息
* tm 的域名信息.
*/
private String tmDomain;
/**
* 存放事务组id
* 存放事务组id.
*/
private String txGroupId;
/**
* 创建时间
* 创建时间.
*/
private String createDate;
/**
* 事务最大等待时间 单位秒
* 事务最大等待时间 单位秒.
*/
private Integer waitMaxTime;
/**
* 执行类名称
* 执行类名称.
*/
private String targetClass;
/**
* 执行方法
* 执行方法.
*/
private String targetMethod;
/**
* 耗时
* 耗时 .
*/
private Long consumeTime;
private Object message;
}

View File

@ -0,0 +1,12 @@
recover:
application:
list : alipay-service,wechat-service,pay-service
serializer :
support: kryo
retry :
max: 10
db:
driver : com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.1.68:3306/tx?useUnicode=true&amp;characterEncoding=utf8
username: xiaoyu
password: Wgj@555888

View File

@ -0,0 +1,8 @@
recover:
application:
list : alipay-service,wechat-service,pay-service
serializer :
support: kryo
retry :
max: 10

View File

@ -0,0 +1,12 @@
recover:
application:
list : alipay-service,wechat-service,pay-service
serializer :
support: kryo
retry :
max: 10
mongo :
url : 192.168.1.68:27017
dbName : happylife
userName : xiaoyu
password : 123456

View File

@ -0,0 +1,13 @@
recover:
application:
list : alipay-service,wechat-service,pay-service
serializer :
support: kryo
retry :
max: 10
redis:
cluster: false
# clusterUrl : 127.0.0.1:70001;127.0.1:7002
hostName : 192.168.1.68
port : 6379
password :

View File

@ -0,0 +1,10 @@
recover:
application:
list : alipay-service,wechat-service,pay-service
serializer :
support: kryo
retry :
max: 10
zookeeper:
host : 192.168.1.132:2181
sessionTimeOut : 3000

View File

@ -1,87 +0,0 @@
#
#
# Copyright 2017-2018 549477611@qq.com(xiaoyu)
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# Lesser General Public License, as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this distribution; if not, see <http://www.gnu.org/licenses/>.
#
#
#\u670D\u52A1\u7AEF\u53E3
server.port=8888
server.context-path=/admin
server.address=0.0.0.0
spring.application.name=raincat-admin
spring.profiles.active=db
# txManager redis \u914D\u7F6E
#\u96C6\u7FA4\u914D\u7F6E
#tx.redis.cluster=true
#tx.redis.cluster.nodes=127.0.0.1:70001;127.0.1:7002
tx.redis.cluster.redirects=20
#\u5355\u673A\u914D\u7F6E
tx.redis.cluster=false
tx.redis.hostName=192.168.1.68
#redis\u4E3B\u673A\u7AEF\u53E3
tx.redis.port=6379
#tx.redis.password=happylifeplat01
# admin\u7BA1\u7406\u540E\u53F0\u7684\u7528\u6237\u540D\uFF0C\u7528\u6237\u53EF\u4EE5\u81EA\u5DF1\u66F4\u6539
tx.admin.userName=admin
# admin\u7BA1\u7406\u540E\u53F0\u7684\u5BC6\u7801\uFF0C\u7528\u6237\u53EF\u4EE5\u81EA\u5DF1\u66F4\u6539
tx.admin.password=admin
#\u91C7\u7528\u4E8C\u9636\u6BB5\u63D0\u4EA4\u9879\u76EE\u7684\u5E94\u7528\u540D\u79F0\u96C6\u5408\uFF0C\u8FD9\u4E2A\u5FC5\u987B\u8981\u586B\u5199
recover.application.list=alipay-service,wechat-service,pay-service
#\u4E8B\u52A1\u8865\u507F\u7684\u5E8F\u5217\u65B9\u5F0F
recover.serializer.support=kryo
#\u4E8B\u52A1\u8865\u507F\u6700\u5927\u91CD\u8BD5\u6B21\u6570
recover.retry.max=10
#dbSuport
recover.db.driver=com.mysql.jdbc.Driver
recover.db.url=jdbc:mysql://192.168.1.68:3306/tx?useUnicode=true&amp;characterEncoding=utf8
recover.db.username=xiaoyu
recover.db.password=Wgj@555888
#redis
recover.redis.cluster=false
recover.redis.hostName=192.168.1.68
recover.redis.port=6379
recover.redis.password=
#recover.redis.clusterUrl=127.0.0.1:70001;127.0.1:7002
#mongo
recover.mongo.url=192.168.1.68:27017
recover.mongo.dbName=happylife
recover.mongo.userName=xiaoyu
recover.mongo.password=123456
#zookeeper
recover.zookeeper.host=192.168.1.132:2181
recover.zookeeper.sessionTimeOut=200000

View File

@ -0,0 +1,21 @@
server:
port: 8888
context-path: /admin
spring:
application:
name: raincat-admin
profiles:
active: mongo
tx:
admin :
userName : admin
password : admin
redis:
hostName: localhost
port : 6379
password:
cluster : false
# nodes: 127.0.0.1:70001;127.0.1:7002
# redirects: 20

View File

@ -7,7 +7,7 @@
<div id="app">
<app></app>
</div>
<a id="serverIpAddress" style="display: none" href="http://192.168.1.109:8888/admin">
<a id="serverIpAddress" style="display: none" href="http://localhost:8888/admin">
</a>
<script type="text/javascript" src="bundle.js"></script></body>
</html>

View File

@ -26,11 +26,13 @@ import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.raincat.common.bean.TransactionRecover;
import com.raincat.common.enums.CompensationActionEnum;
import com.raincat.common.holder.LogUtil;
import com.raincat.core.disruptor.event.TxTransactionEvent;
import com.raincat.core.disruptor.factory.TxTransactionEventFactory;
import com.raincat.core.disruptor.handler.TxTransactionEventHandler;
import com.raincat.core.disruptor.translator.TxTransactionEventTranslator;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -43,9 +45,11 @@ import java.util.concurrent.atomic.AtomicInteger;
* @author xiaoyu(Myth)
*/
@Component
@Slf4j
public class TxTransactionEventPublisher implements DisposableBean {
/** logger */
private static final Logger LOGGER = LoggerFactory.getLogger(TxTransactionEventPublisher.class);
private Disruptor<TxTransactionEvent> disruptor;
@Autowired
@ -65,22 +69,18 @@ public class TxTransactionEventPublisher implements DisposableBean {
disruptor.setDefaultExceptionHandler(new ExceptionHandler<TxTransactionEvent>() {
@Override
public void handleEventException(Throwable ex, long sequence, TxTransactionEvent event) {
log.error("DisruptorException 捕捉异常! -> ", ex);
log.error("Disruptor handleEventException 异常," +
"执行动作 Type: [{}], " +
"TransactionRecover 信息:[{}]", event.getType(), event.getTransactionRecover());
LogUtil.error(LOGGER,()-> "Disruptor handleEventException:"
+ event.getType() + event.getTransactionRecover().toString() );
}
@Override
public void handleOnStartException(Throwable ex) {
log.error("DisruptorException 启动异常 [{}]", ex);
LogUtil.error(LOGGER,()-> "Disruptor start exception");
}
@Override
public void handleOnShutdownException(Throwable ex) {
log.error("DisruptorException 关闭异常 [{}]", ex);
LogUtil.error(LOGGER,()-> "Disruptor close Exception ");
}
});
disruptor.start();