org.apache.rocketmq.acl.common.SessionCredentials Java Examples

The following examples show how to use org.apache.rocketmq.acl.common.SessionCredentials. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecKillChargeOrderProducer.java    From seckill-rocketmq with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    defaultMQProducer =
            new DefaultMQProducer
                    (MessageProtocolConst.SECKILL_CHARGE_ORDER_TOPIC.getProducerGroup(),
                            new AclClientRPCHook(new SessionCredentials(aclAccessKey, aclAccessSecret)));
    defaultMQProducer.setNamesrvAddr(namesrvConfig.nameSrvAddr());
    // 发送失败重试次数
    defaultMQProducer.setRetryTimesWhenSendFailed(3);
    try {
        defaultMQProducer.start();
    } catch (MQClientException e) {
        LOGGER.error("[秒杀订单生产者]--SecKillChargeOrderProducer加载异常!e={}", LogExceptionWapper.getStackTrace(e));
        throw new RuntimeException("[秒杀订单生产者]--SecKillChargeOrderProducer加载异常!", e);
    }
    LOGGER.info("[秒杀订单生产者]--SecKillChargeOrderProducer加载完成!");
}
 
Example #2
Source File: PlainAccessValidatorTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test(expected = AclException.class)
public void validateNullAccessKeyTest() {
    SessionCredentials sessionCredentials=new SessionCredentials();
    sessionCredentials.setAccessKey("RocketMQ1");
    sessionCredentials.setSecretKey("1234");
    AclClientRPCHook aclClientRPCHook=new AclClientRPCHook(sessionCredentials);
    SendMessageRequestHeader messageRequestHeader = new SendMessageRequestHeader();
    messageRequestHeader.setTopic("topicB");
    RemotingCommand remotingCommand = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, messageRequestHeader);
    aclClientRPCHook.doBeforeRequest("", remotingCommand);

    ByteBuffer buf = remotingCommand.encodeHeader();
    buf.getInt();
    buf = ByteBuffer.allocate(buf.limit() - buf.position()).put(buf);
    buf.position(0);
    PlainAccessResource accessResource = (PlainAccessResource) plainAccessValidator.parse(RemotingCommand.decode(buf), "192.168.1.1");
    plainAccessValidator.validate(accessResource);
}
 
Example #3
Source File: PlainAccessValidatorTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test(expected = AclException.class)
public void validateErrorSecretKeyTest() {
    SessionCredentials sessionCredentials=new SessionCredentials();
    sessionCredentials.setAccessKey("RocketMQ");
    sessionCredentials.setSecretKey("1234");
    AclClientRPCHook aclClientRPCHook=new AclClientRPCHook(sessionCredentials);
    SendMessageRequestHeader messageRequestHeader = new SendMessageRequestHeader();
    messageRequestHeader.setTopic("topicB");
    RemotingCommand remotingCommand = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, messageRequestHeader);
    aclClientRPCHook.doBeforeRequest("", remotingCommand);

    ByteBuffer buf = remotingCommand.encodeHeader();
    buf.getInt();
    buf = ByteBuffer.allocate(buf.limit() - buf.position()).put(buf);
    buf.position(0);
    PlainAccessResource accessResource = (PlainAccessResource) plainAccessValidator.parse(RemotingCommand.decode(buf), "192.168.1.1");
    plainAccessValidator.validate(accessResource);
}
 
Example #4
Source File: SecKillChargeOrderConsumer.java    From seckill-rocketmq with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    defaultMQPushConsumer =
            new DefaultMQPushConsumer(
                MessageProtocolConst.SECKILL_CHARGE_ORDER_TOPIC.getConsumerGroup(),
                    new AclClientRPCHook(new SessionCredentials(aclAccessKey, aclAccessSecret)),
                    // 平均分配队列算法,hash
                    new AllocateMessageQueueAveragely());
    defaultMQPushConsumer.setNamesrvAddr(namesrvConfig.nameSrvAddr());
    // 从头开始消费
    defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    // 消费模式:集群模式
    // 集群:同一条消息 只会被一个消费者节点消费到
    // 广播:同一条消息 每个消费者都会消费到
    defaultMQPushConsumer.setMessageModel(MessageModel.CLUSTERING);
    // 注册监听器
    defaultMQPushConsumer.registerMessageListener(messageListener);
    // 设置每次拉取的消息量,默认为1
    defaultMQPushConsumer.setConsumeMessageBatchMaxSize(1);
    // 订阅所有消息
    try {
        defaultMQPushConsumer.subscribe(MessageProtocolConst.SECKILL_CHARGE_ORDER_TOPIC.getTopic(), "*");
        // 启动消费者
        defaultMQPushConsumer.start();
    } catch (MQClientException e) {
        LOGGER.error("[秒杀下单消费者]--SecKillChargeOrderConsumer加载异常!e={}", LogExceptionWapper.getStackTrace(e));
        throw new RuntimeException("[秒杀下单消费者]--SecKillChargeOrderConsumer加载异常!", e);
    }
    LOGGER.info("[秒杀下单消费者]--SecKillChargeOrderConsumer加载完成!");
}
 
Example #5
Source File: RocketMQUtil.java    From rocketmq-spring with Apache License 2.0 5 votes vote down vote up
public static RPCHook getRPCHookByAkSk(Environment env, String accessKeyOrExpr, String secretKeyOrExpr) {
    String ak, sk;
    try {
        ak = env.resolveRequiredPlaceholders(accessKeyOrExpr);
        sk = env.resolveRequiredPlaceholders(secretKeyOrExpr);
    } catch (Exception e) {
        // Ignore it
        ak = null;
        sk = null;
    }
    if (!StringUtils.isEmpty(ak) && !StringUtils.isEmpty(sk)) {
        return new AclClientRPCHook(new SessionCredentials(ak, sk));
    }
    return null;
}
 
Example #6
Source File: RocketMQUtil.java    From rocketmq-spring with Apache License 2.0 5 votes vote down vote up
public static String getInstanceName(RPCHook rpcHook, String identify) {
    String separator = "|";
    StringBuilder instanceName = new StringBuilder();
    SessionCredentials sessionCredentials = ((AclClientRPCHook) rpcHook).getSessionCredentials();
    instanceName.append(sessionCredentials.getAccessKey())
        .append(separator).append(sessionCredentials.getSecretKey())
        .append(separator).append(identify)
        .append(separator).append(UtilAll.getPid());
    return instanceName.toString();
}
 
Example #7
Source File: RocketMQUtilTest.java    From rocketmq-spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetInstanceName() {
    String ak = "ak";
    String sk = "sk";
    String consumerGroup = "consumerGroup";
    RPCHook rpcHook = new AclClientRPCHook(new SessionCredentials(ak, sk));
    String expected = "ak|sk|consumerGroup|";
    assertEquals(expected + UtilAll.getPid(), RocketMQUtil.getInstanceName(rpcHook, consumerGroup));
}
 
Example #8
Source File: PlainAccessValidatorTest.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    System.setProperty("rocketmq.home.dir", "src/test/resources");
    System.setProperty("rocketmq.acl.plain.file", "/conf/plain_acl.yml");
    plainAccessValidator = new PlainAccessValidator();
    sessionCredentials = new SessionCredentials();
    sessionCredentials.setAccessKey("RocketMQ");
    sessionCredentials.setSecretKey("12345678");
    sessionCredentials.setSecurityToken("87654321");
    aclClient = new AclClientRPCHook(sessionCredentials);
}
 
Example #9
Source File: AclClient.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
static RPCHook getAclRPCHook() {
    return new AclClientRPCHook(new SessionCredentials(ACL_ACCESS_KEY,ACL_SECRET_KEY));
}
 
Example #10
Source File: PlainAccessValidator.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Override
public AccessResource parse(RemotingCommand request, String remoteAddr) {
    PlainAccessResource accessResource = new PlainAccessResource();
    if (remoteAddr != null && remoteAddr.contains(":")) {
        accessResource.setWhiteRemoteAddress(remoteAddr.substring(0, remoteAddr.lastIndexOf(':')));
    } else {
        accessResource.setWhiteRemoteAddress(remoteAddr);
    }

    accessResource.setRequestCode(request.getCode());

    if (request.getExtFields() == null) {
        // If request's extFields is null,then return accessResource directly(users can use whiteAddress pattern)
        // The following logic codes depend on the request's extFields not to be null.
        return accessResource;
    }
    accessResource.setAccessKey(request.getExtFields().get(SessionCredentials.ACCESS_KEY));
    accessResource.setSignature(request.getExtFields().get(SessionCredentials.SIGNATURE));
    accessResource.setSecretToken(request.getExtFields().get(SessionCredentials.SECURITY_TOKEN));

    try {
        switch (request.getCode()) {
            case RequestCode.SEND_MESSAGE:
                accessResource.addResourceAndPerm(request.getExtFields().get("topic"), Permission.PUB);
                break;
            case RequestCode.SEND_MESSAGE_V2:
                accessResource.addResourceAndPerm(request.getExtFields().get("b"), Permission.PUB);
                break;
            case RequestCode.CONSUMER_SEND_MSG_BACK:
                accessResource.addResourceAndPerm(request.getExtFields().get("originTopic"), Permission.PUB);
                accessResource.addResourceAndPerm(getRetryTopic(request.getExtFields().get("group")), Permission.SUB);
                break;
            case RequestCode.PULL_MESSAGE:
                accessResource.addResourceAndPerm(request.getExtFields().get("topic"), Permission.SUB);
                accessResource.addResourceAndPerm(getRetryTopic(request.getExtFields().get("consumerGroup")), Permission.SUB);
                break;
            case RequestCode.QUERY_MESSAGE:
                accessResource.addResourceAndPerm(request.getExtFields().get("topic"), Permission.SUB);
                break;
            case RequestCode.HEART_BEAT:
                HeartbeatData heartbeatData = HeartbeatData.decode(request.getBody(), HeartbeatData.class);
                for (ConsumerData data : heartbeatData.getConsumerDataSet()) {
                    accessResource.addResourceAndPerm(getRetryTopic(data.getGroupName()), Permission.SUB);
                    for (SubscriptionData subscriptionData : data.getSubscriptionDataSet()) {
                        accessResource.addResourceAndPerm(subscriptionData.getTopic(), Permission.SUB);
                    }
                }
                break;
            case RequestCode.UNREGISTER_CLIENT:
                final UnregisterClientRequestHeader unregisterClientRequestHeader =
                    (UnregisterClientRequestHeader) request
                        .decodeCommandCustomHeader(UnregisterClientRequestHeader.class);
                accessResource.addResourceAndPerm(getRetryTopic(unregisterClientRequestHeader.getConsumerGroup()), Permission.SUB);
                break;
            case RequestCode.GET_CONSUMER_LIST_BY_GROUP:
                final GetConsumerListByGroupRequestHeader getConsumerListByGroupRequestHeader =
                    (GetConsumerListByGroupRequestHeader) request
                        .decodeCommandCustomHeader(GetConsumerListByGroupRequestHeader.class);
                accessResource.addResourceAndPerm(getRetryTopic(getConsumerListByGroupRequestHeader.getConsumerGroup()), Permission.SUB);
                break;
            case RequestCode.UPDATE_CONSUMER_OFFSET:
                final UpdateConsumerOffsetRequestHeader updateConsumerOffsetRequestHeader =
                    (UpdateConsumerOffsetRequestHeader) request
                        .decodeCommandCustomHeader(UpdateConsumerOffsetRequestHeader.class);
                accessResource.addResourceAndPerm(getRetryTopic(updateConsumerOffsetRequestHeader.getConsumerGroup()), Permission.SUB);
                accessResource.addResourceAndPerm(updateConsumerOffsetRequestHeader.getTopic(), Permission.SUB);
                break;
            default:
                break;

        }
    } catch (Throwable t) {
        throw new AclException(t.getMessage(), t);
    }

    // Content
    SortedMap<String, String> map = new TreeMap<String, String>();
    for (Map.Entry<String, String> entry : request.getExtFields().entrySet()) {
        if (!SessionCredentials.SIGNATURE.equals(entry.getKey())
                && !MixAll.UNIQUE_MSG_QUERY_FLAG.equals(entry.getKey())) {
            map.put(entry.getKey(), entry.getValue());
        }
    }
    accessResource.setContent(AclUtils.combineRequestContent(request, map));
    return accessResource;
}