1

Is Spring capable of using different database endpoints for failover and query routing - ie, reads go to the read cluster, writes go to the master? And specifying which endpoint to use per Method in a Service class

For example, say we have the following Service. The save and delete can go to the master endpoint to write, whilst the rest can go to the 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);
    }
}
Christian
  • 3,708
  • 3
  • 39
  • 60

1 Answers1

0

To quote this answer stackoverflow.com/a/43326808/935122

The Best Way is to use MySQL Connector/J replication aware driver configuration . Your Connection string will be as below

jdbc:mysql:replication://[master host][:port],[slave host 1][:port][,[slave host 2][:port]]...[/[database]]

Once you tag a transaction as read only , it will be automatically routed to read only slaves

https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-master-slave-replication-connection.html

Christian
  • 3,708
  • 3
  • 39
  • 60