1.pom文件
<!--redis支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--mongo支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.yml配置
spring:
redis:
host: 127.0.0.1
port: 6379
application:
name: smart-bop
cloud:
config:
profile: dev
server:
port: '${web_server_port:8081}'
tomcat:
basedir: tomcat
accesslog:
enabled: true
directory: logs
logging:
file: log/smart-bop.log
level:
ROOT: INFO
org.springframework.web.filter.CommonsRequestLoggingFilter: DEBUG
com.eingsoft.emop: DEBUG
mongodb:
uri: 'mongodb://root:Rdis2fun@192.168.1.18:27017,192.168.1.18:27018,192.168.1.18:27019/bop?authSource=admin&connect=replicaSet&readPreference=secondaryPreferred&safe=true&authMechanism=SCRAM-SHA-1&maxPoolSize=500&minPoolSize=10'
classification:
root: ICM
3.添加mongo的事物整合
@Value("${mongodb.uri}")
private String mongodbUri;
@Beanpublic MongoDbFactory mongoFactory() {
return new SimpleMongoDbFactory(new MongoClientURI(mongodbUri));
}
@Bean(name = "mongoTemplate")
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoFactory());
}
@Bean(name = "mongoTransactionManager")
public MongoTransactionManager mongoTransactionManager(MongoTemplate template) {
return new MongoTransactionManager(template.getMongoDbFactory());
}
@Beanpublic ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
4.业务代码(注释掉的可以不需要)
//TODO 保证mongodb 与 redis 数据同步ParameterDefinition-测试909
//注解保证mongo事物(声明式事物)
@Transactional
//@Transactional(rollbackFor = { Exception.class })
public void save(ParameterDefinition parameterDefinition) throws Exception{
//开启redis事务权限(采用手动事务)
parameterDefinitionRedisTemplate.setEnableTransactionSupport(true);
try {
//开启redis事务
parameterDefinitionRedisTemplate.multi();
String name = parameterDefinition.getName();
//直接更新redis再通知其他节点,跟新map
String redisKry = Constant.Parameter_Definition_Sufix+name;
//更新redis parameterDefinitionRedisTemplate.delete(redisKry);
parameterDefinitionRedisTemplate.opsForValue().set(redisKry, parameterDefinition);
//保存到mongo if (parameterDefinition.getRuntimeType() == null) {
parameterDefinition.setStaticType(ParameterType.valOf(parameterDefinition.getTypeName()));
parameterDefinition.setRuntimeType(ParameterType.valOf(parameterDefinition.getTypeName()));
}
//测试回滚 int i = 1/0;
parameterDefRepository.save(parameterDefinition);
//redis成功就提交 parameterDefinitionRedisTemplate.exec();
} catch (Exception e) {
//redis失败了就回滚 parameterDefinitionRedisTemplate.discard();
log.error(e);
log.error("ParameterDefinitionService save发生异常,回滚mongo与redis");
//TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//自定义抛出异常,方便被aop的异常通知捕获到
//throw new Exception("ParameterDefinitionService save发生异常,回滚mongo与redis"); }
}
效果已经验证成功啦,这里就不演示啦。