Spring是否能够使用不同的数据库端点进行故障转移和查询路由 - 即,读取到读取群集,写入主节点?并在Service
类
例如,假设我们有以下服务。 save
和delete
可以转到主端点进行写入,其余的可以转到read cluster
。
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Autowired
private AttributeService attributeService;
// -------------------------------------------------------------
private boolean nameAvailable(String name, Long id) {
if (id == null) {
return productRepository.findByNameEquals(name) == null;
} else {
return productRepository.findByNameEqualsAndIdIsNot(name, id) == null;
}
}
public synchronized void save(Product product, BindingResult result) {
// synchronized to avoid name duplication
if (!result.hasErrors()) {
if (!nameAvailable(product.getName(), product.getId())) {
result.addError(new FieldError("product", "name", "must be unique"));
} else {
productRepository.save(product);
}
}
}
public void delete(Long id) {
productRepository.delete(id);
}
// -------------------------------------------------------------
public Page<Product> getProducts(PageRequest pageRequest) {
return productRepository.findAll(pageRequest);
}
public Product getProduct(Long id) throws ProductNotFoundException {
Product product = productRepository.findOne(id);
if (product == null) {
throw new ProductNotFoundException();
}
return product;
}
public Page<Attribute> getAttributes(Product product, Pageable pageable) {
return attributeService.getAttributes(product, pageable);
}
}
答案 0 :(得分:0)
引用此答案stackoverflow.com/a/43326808/935122
最佳方式是使用MySQL Connector / J复制感知驱动程序配置。您的连接字符串将如下所示
jdbc:mysql:replication://[master host][:port],[slave host 1][:port][,[slave host 2][:port]]...[/[database]]
将事务标记为只读后,它将自动路由到只读从设备
https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-master-slave-replication-connection.html