今天发现项目在rocketMQ消费成功,但是数据库未更新,也不报任何错。然后我打开日志DEBUG模式发现在消费结束后只打印了``Initiating transaction commit``和select语句并没有打印insert语句。
然后我加了``TestController``在消费的时候使用http请求就可以正常更新,初步怀疑时sharding的问题。
java内发送http请求示例代码:
package org.fd;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
@Component
public class TestHttp {
public void handleHttp(String jsonParam, String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(url);
request.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity s = new StringEntity(jsonParam, StandardCharsets.UTF_8);
s.setContentEncoding("UTF-8");
s.setContentType("application/json;charset=UTF-8");
request.setEntity(s);
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line).append(NL);
}
in.close();
if (code == 200) {
logger.info("接口:{},请求成功:" + sb.toString(), url);
} else if (code == 500) {
throw new Exception("服务器错误:" + sb + ",url:" + url);
} else {
throw new Exception("接口未知的情况,code=" + code + "," + sb + ",url:" + url);
}
} catch (Exception e) {
throw new Exception("接口调用出现异常……");
}
}
}
接下来我去掉sharding分库分表后测试,果然能插进去数据。但是加了sharing以后插入不进去数据了。然后一步一步DEBUG到sharding事务提交那里发现有多个事务管理器,但是sharding默认使用了第一个,事务正常提交因为没有获取到JPA的事务管理器(我们的项目使用JPA操作数据库),所以事务没有提交失效了,所以就写了如下自定义事务管理器配置类来指定拥有多个事务管理器时使用JPA的事务管理器。
解决方案:
package org.fd;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
@Configuration
public class TransactionManagerConfig implements TransactionManagementConfigurer {
@Resource(name="transactionManager")
private PlatformTransactionManager txManager;
/**
* 创建事务管理器
* @param factory
* @return JPA事务管理器
*/
@Bean(name = "transactionManager")
public PlatformTransactionManager txManager(EntityManagerFactory factory) {
return new JpaTransactionManager(factory);
}
/**
* @param
* @return 代表在拥有多个事务管理器的情况下默认使用的事务管理
*/
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return txManager;
}
}
然后启动测试果然解决!