I am using one existing spring boot annotation and want to set the attribute value dynamically using spring expression and want to have one constant value as a prefix,
sample Code snippet
@KafkaListener(topics="${topic.name}", groupId="#{'consumergroup' (int)(java.lang.Math).random() }")
public void consumerMethod(){
}
I want to create a new consumer group for each new container using the above kind of implementation.
But I am facing the below exception.
Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lparen(()
kindly help me to either use template spring EL or any other way I can use to set dynamic consumer group id with the constant prefix.
CodePudding user response:
groupId="#{'consumergroup' (100 * T(Math).random()).intValue() }"
- There is no
cast
operator in SpEL. Just because it uses aConversionService
internally to convert from one type to another. I useintValue()
any way because the result ofrandom()
isDouble
(notdouble
) - SpEL does coercion into type wrappers for API convenience. - The
java.lang
is imported into SpEL context automatically. No need to add it forMath
type. 100 *
. SeeMath.random()
JavaDocs: it returns the value between0.0
and1.0
. So, casting toint
would always bring you only0
. The casting doesn't do rounding.
Also see Spring Boot configuration properties feature where you can use random value for the groupId
:
spring.kafka.consumer.group-id=consumergroup${random.int}