更新时间:2022-12-27 GMT+08:00
分享

非事务中使用强制路由

除了根据路由算法配置路由,sdk还支持通过注解@DynamicRoute强制指定路由,且相比路由算法,注解指定路由优先级更高。存在注解指定路由的场景下,优先根据注解指定进行路由。

注解@DynamicRoute指定路由分为两部分:source和hint,可单独只指定source或hint,也可一起组合使用。

source用于选择数据中心,可以填"dc1"/"dc2"/"ACTIVE"。填"dc1"时,则强制路由到dc1数据中心,不管此时的路由算法为哪种,也不管sql类型是读还是写;同理,填“dc2”时,强制路由到dc2数据中心;比较特殊的是“ACTIVE”,此时路由到active指示的数据中心,同样不管路由算法为哪种,也不管sql类型为哪种。

hint用于读写分离场景,可以填HintType.READMASTER/HintType.READSLAVE/HintType.NONE。其中,HintType.READMASTER为指定从主库读取,HintType.READSLAVE为指定从从库读取,HintType.NONE为不指定。当存在从库,且从库可读(DCG指示从库状态可读,若不对接mas平台或DCG不指示,默认从库可读)时,默认从从库读取。

用法如下:

@DynamicRoute注解支持在方法、类上添加,如下:

方法上添加注解:

@DynamicRoute(source = "dc2", hint = HintType.READMASTER)
@RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
public UserModel query(@PathVariable("id") Long id) {
    return userMapper.select(id);
}

类上添加注解:此时针对该类的所有方法注解都生效

@DynamicRoute(source = "dc2", hint = HintType.READMASTER)
@RestController
@RequestMapping(value = "/v1/user", produces = {"application/json;charset=UTF-8"})
public class TestUserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
    public UserModel query(@PathVariable("id") Long id) {
        return userMapper.select(id);
    }
}
分享:

    相关文档

    相关产品