/
RabbitmqGrailsPlugin.groovy
247 lines (215 loc) · 12.5 KB
/
RabbitmqGrailsPlugin.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import org.codehaus.groovy.grails.commons.GrailsClassUtils as GCU
import org.grails.rabbitmq.AutoQueueMessageListenerContainer
import org.grails.rabbitmq.RabbitDynamicMethods
import org.grails.rabbitmq.RabbitQueueBuilder
import org.springframework.amqp.core.Binding
import org.springframework.amqp.core.Queue
import org.springframework.amqp.rabbit.core.RabbitAdmin
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter
import static org.springframework.amqp.core.Binding.DestinationType.QUEUE
import org.grails.rabbitmq.RabbitConfigurationHolder
class RabbitmqGrailsPlugin {
// the plugin version
def version = "0.3.4-SNAPSHOT"
// the version or versions of Grails the plugin is designed for
def grailsVersion = "1.2 > *"
// the other plugins this plugin depends on
def dependsOn = [:]
// resources that are excluded from plugin packaging
def pluginExcludes = [
"grails-app/views/error.gsp",
"grails-app/services/**",
"grails-app/controllers/**",
"grails-app/views/message/*",
"grails-app/conf/Config.groovy",
"src/groovy/org/grails/rabbitmq/test/**",
"**/.gitignore"
]
def author = "Jeff Brown"
def authorEmail = "jeff.brown@springsource.com"
def title = "RabbitMQ Plugin"
def description = "The RabbitMQ plugin provides integration with the RabbitMQ Messaging System."
def license = "APACHE"
def organization = [ name: "SpringSource", url: "http://www.springsource.org/" ]
def developers = [ [ name: "Peter Ledbrook", email: "pledbrook@vmware.com" ] ]
def issueManagement = [ system: "JIRA", url: "http://jira.codehaus.org/browse/GRAILSPLUGINS" ]
def scm = [ url: "https://github.com/grails-plugins/grails-rabbitmq" ]
// URL to the plugin's documentation
def documentation = "http://grails-plugins.github.com/grails-rabbitmq/"
def loadAfter = ['services']
def observe = ['*']
private static LISTENER_CONTAINER_SUFFIX = '_MessageListenerContainer'
def doWithSpring = {
def rabbitmqConfig = application.config.rabbitmq
def configHolder = new RabbitConfigurationHolder(rabbitmqConfig)
def connectionFactoryConfig = rabbitmqConfig?.connectionfactory
def connectionFactoryUsername = connectionFactoryConfig?.username
def connectionFactoryPassword = connectionFactoryConfig?.password
def connectionFactoryVirtualHost = connectionFactoryConfig?.virtualHost
def connectionFactoryHostname = connectionFactoryConfig?.hostname
def connectionChannelCacheSize = connectionFactoryConfig?.channelCacheSize ?: 10
def messageConverterBean = rabbitmqConfig.messageConverterBean
if(!connectionFactoryUsername || !connectionFactoryPassword || !connectionFactoryHostname) {
log.error 'RabbitMQ connection factory settings (rabbitmq.connectionfactory.username, rabbitmq.connectionfactory.password and rabbitmq.connectionfactory.hostname) must be defined in Config.groovy'
} else {
log.debug "Connecting to rabbitmq ${connectionFactoryUsername}@${connectionFactoryHostname} with ${configHolder.getDefaultConcurrentConsumers()} consumers."
def connectionFactoryClassName = connectionFactoryConfig?.className ?: 'org.springframework.amqp.rabbit.connection.CachingConnectionFactory'
def parentClassLoader = getClass().classLoader
def loader = new GroovyClassLoader(parentClassLoader)
def connectionFactoryClass = loader.loadClass(connectionFactoryClassName)
rabbitMQConnectionFactory(connectionFactoryClass, connectionFactoryHostname) {
username = connectionFactoryUsername
password = connectionFactoryPassword
channelCacheSize = connectionChannelCacheSize
if (connectionFactoryVirtualHost) {
virtualHost = connectionFactoryVirtualHost
}
}
rabbitTemplate(RabbitTemplate) {
connectionFactory = rabbitMQConnectionFactory
if (messageConverterBean) messageConverter = ref(messageConverterBean)
}
adm(RabbitAdmin, rabbitMQConnectionFactory)
Set registeredServices = new HashSet()
application.serviceClasses.each { service ->
def serviceClass = service.clazz
def propertyName = service.propertyName
def transactional = service.transactional
if (!(rabbitmqConfig."${propertyName}".transactional instanceof ConfigObject)) {
transactional = rabbitmqConfig."${propertyName}".transactional as Boolean
}
def rabbitQueue = GCU.getStaticPropertyValue(serviceClass, 'rabbitQueue')
if(rabbitQueue) {
if(configHolder.isServiceEnabled(service)) {
def serviceConcurrentConsumers = configHolder.getServiceConcurrentConsumers(service)
log.info("Setting up rabbitmq listener for ${service.clazz} with ${serviceConcurrentConsumers} consumer(s)")
if(!registeredServices.add(propertyName)){
throw new IllegalArgumentException("Unable to initialize rabbitmq listeners properly. More than one service named ${propertyName}.")
}
"${propertyName}${LISTENER_CONTAINER_SUFFIX}"(SimpleMessageListenerContainer) {
// We manually start the listener once we have attached the
// service in doWithApplicationContext.
autoStartup = false
channelTransacted = transactional
connectionFactory = rabbitMQConnectionFactory
concurrentConsumers = serviceConcurrentConsumers
queueNames = rabbitQueue
}
} else {
log.info("Not listening to ${service.clazz} it is disabled in configuration")
}
}
else {
def rabbitSubscribe = GCU.getStaticPropertyValue(serviceClass, 'rabbitSubscribe')
if (rabbitSubscribe) {
if (!(rabbitSubscribe instanceof CharSequence) && !(rabbitSubscribe instanceof Map)) {
log.error "The 'rabbitSubscribe' property on service ${service.fullName} must be a string or a map"
}
else {
if(configHolder.isServiceEnabled(service)) {
def serviceConcurrentConsumers = configHolder.getServiceConcurrentConsumers(service)
log.info("Setting up rabbitmq listener for ${service.clazz} with ${serviceConcurrentConsumers} consumer(s)")
if(!registeredServices.add(propertyName)){
throw new IllegalArgumentException("Unable to initialize rabbitmq listeners properly. More than one service named ${propertyName}.")
}
"${propertyName}${LISTENER_CONTAINER_SUFFIX}"(AutoQueueMessageListenerContainer) {
// We manually start the listener once we have attached the
// service in doWithApplicationContext.
autoStartup = false
channelTransacted = transactional
connectionFactory = rabbitMQConnectionFactory
concurrentConsumers = serviceConcurrentConsumers
if (rabbitSubscribe instanceof Map) {
exchangeBeanName = "grails.rabbit.exchange.${rabbitSubscribe.name}"
routingKey = rabbitSubscribe.routingKey ?: '#'
}
else {
exchangeBeanName = "grails.rabbit.exchange.${rabbitSubscribe}"
}
}
} else {
log.info("Not listening to ${service.clazz} it is disabled in configuration")
}
}
}
}
}
def queuesConfig = application.config.rabbitmq?.queues
if(queuesConfig) {
def queueBuilder = new RabbitQueueBuilder()
queuesConfig = queuesConfig.clone()
queuesConfig.delegate = queueBuilder
queuesConfig.resolveStrategy = Closure.DELEGATE_FIRST
queuesConfig()
// Deal with declared exchanges first.
queueBuilder.exchanges?.each { exchange ->
if (log.debugEnabled) {
log.debug "Registering exchange '${exchange.name}'"
}
"grails.rabbit.exchange.${exchange.name}"(exchange.type, exchange.name,
Boolean.valueOf(exchange.durable),
Boolean.valueOf(exchange.autoDelete),
exchange.arguments)
}
// Next, the queues.
queueBuilder.queues?.each { queue ->
if (log.debugEnabled) {
log.debug "Registering queue '${queue.name}'"
}
"grails.rabbit.queue.${queue.name}"(Queue, queue.name,
Boolean.valueOf(queue.durable),
Boolean.valueOf(queue.exclusive),
Boolean.valueOf(queue.autoDelete),
queue.arguments,
)
}
// Finally, the bindings between exchanges and queues.
queueBuilder.bindings?.each { binding ->
if (log.debugEnabled) {
log.debug "Registering binding between exchange '${binding.exchange}' & queue '${binding.queue}'"
}
def args = [ ref("grails.rabbit.exchange.${binding.exchange}"), ref ("grails.rabbit.queue.${binding.queue}") ]
if (binding.rule) {
log.debug "Binding with rule '${binding.rule}'"
// Support GString and String for the rule. Other types of rule (Map
// is the only valid option atm) are passed through as is.
args << (binding.rule instanceof CharSequence ? binding.rule.toString() : binding.rule)
}
"grails.rabbit.binding.${binding.exchange}.${binding.queue}"(Binding, binding.queue, QUEUE, binding.exchange, binding.rule, binding.arguments )
}
}
}
}
def doWithDynamicMethods = { appCtx ->
addDynamicMessageSendingMethods application.allClasses, appCtx
}
private addDynamicMessageSendingMethods(classes, ctx) {
if(ctx.rabbitMQConnectionFactory) {
classes.each { clz ->
RabbitDynamicMethods.applyAllMethods(clz, ctx)
}
}
}
def doWithApplicationContext = { applicationContext ->
def rabbitTemplate = applicationContext.getBean('rabbitTemplate', RabbitTemplate.class)
def containerBeans = applicationContext.getBeansOfType(SimpleMessageListenerContainer)
containerBeans.each { beanName, bean ->
if(beanName.endsWith(LISTENER_CONTAINER_SUFFIX)) {
def adapter = new MessageListenerAdapter()
def serviceName = beanName - LISTENER_CONTAINER_SUFFIX
adapter.delegate = applicationContext.getBean(serviceName)
adapter.messageConverter = rabbitTemplate.messageConverter
bean.messageListener = adapter
// Now that the listener is properly configured, we can start it.
bean.start()
}
}
}
def onChange = { evt ->
if(evt.source instanceof Class) {
addDynamicMessageSendingMethods ([evt.source], evt.ctx)
}
}
}