2014年9月30日火曜日

groovyとRabbitMQのHTTP APIを使用して、queueを作成する

groovyとRabbitMQのHTTP APIを使用して、queueを作成するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.*
import org.apache.http.client.methods.*
import org.apache.http.client.protocol.*
import org.apache.http.impl.auth.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import org.apache.http.entity.*
import org.apache.http.message.*
import org.apache.http.protocol.*
import org.apache.http.conn.*
import org.apache.http.*
import groovy.json.*

ConnectionKeepAliveStrategy ckas = new ConnectionKeepAliveStrategy() {
  public long getKeepAliveDuration(HttpResponse response, HttpContext context)
  {
    HeaderElementIterator it = new BasicHeaderElementIterator(
      response.headerIterator(HTTP.CONN_KEEP_ALIVE))
    while(it.hasNext()){
      HeaderElement he = it.nextElement()
      if( he.value != null && he.param.equalsIgnoreCase("timeout") ){
        try
        {
          return Long.parseLong(he.value) * 1000
        }
        catch(NumberFormatException nfex){}
      }
    }
    return 30 * 1000
  }
}
def host = "192.168.1.219"
def port = 15672
def user = "guest"
def pass = "guest"

CredentialsProvider credsProvider = new BasicCredentialsProvider()
credsProvider.setCredentials(
  new AuthScope(host, port),
  new UsernamePasswordCredentials(user, pass)
)
AuthCache authCache = new BasicAuthCache()
HttpHost targetHost = new HttpHost(host, port, "http")
BasicScheme basicAuth = new BasicScheme()
authCache.put(targetHost, basicAuth)
HttpClientContext context = HttpClientContext.create()
context.setCredentialsProvider(credsProvider)
context.setAuthCache(authCache)

CloseableHttpClient httpclient = HttpClients.custom()
  .setKeepAliveStrategy(ckas)
  .build()
httpclient.withCloseable {
  // queueの作成
  def queue = "test_queue1"
  def method = new HttpPut("http://${host}:${port}/api/queues/%2f/${queue}")
  def json = new JsonBuilder()
  json (
    auto_delete:false, durable:true
  )
  method.setHeader("Content-Type", "application/json; charset=utf-8")
  method.setEntity(new StringEntity(json.toString(), "UTF-8"))
  response = httpclient.execute(method, context)
  println response.getStatusLine().getStatusCode()
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

0 件のコメント:

コメントを投稿