在进行JMS开发的过程中我们首先要获得JMS server 的context,然后通过 context 获取 ConnectionFactory、Connection 和 Session 等。为了方便开发,我就抛砖引玉写了个JMS工具类,这样就能简化我们的JMS开发。
一、资源文件
JNDI_FACTORY=weblogic.jndi.WLInitialContextFactory
URL=t3\://localhost\:7001
我这里只写了两个参数值,其实我们也可以把JNDI也配置进去,这样在生成 Queue 和 Topic 的时候也很简便。
二、JMSUtil类
1 /**
2
3 * Auther: orientson
4
5 * Version:JMSUtil1.0
6
7 * Date:2011-03-24
8
9 */
10
11 public class JMSUtil {
12
13
14 //获取资源文件中的参数
15 public static Map<String,String> getFactoryAndUrl(){
16 Map<String,String> map = new HashMap<String,String>();
17 Properties props = new Properties();
18 try {
19 props.load(JMSUtil.class.getClassLoader().getResourceAsStream("jms.properties"));
20 map.put("JNDI_FACTORY", props.getProperty("JNDI_FACTORY"));
21 map.put("URL", props.getProperty("URL"));
22 } catch (IOException e) {
23 e.printStackTrace();
24 }
25 return map;
26 }
27
28
29 //获取Context的方法
30 public static InitialContext getInitialContext(){
31 Map<String,String> map = getFactoryAndUrl();
32 String JNDI_FACTORY = map.get("JNDI_FACTORY");
33 String URL = map.get("URL");
34
35 InitialContext ctx = null;
36 Hashtable<String, String> env = new Hashtable<String, String>();
37 env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
38 env.put(Context.PROVIDER_URL, URL);
39 try {
40 ctx = new InitialContext(env);
41 } catch (NamingException e) {
42 e.printStackTrace();
43 }
44 return ctx;
45 }
46
47 public static void close(Connection conn){
48 if(conn != null){
49 try {
50 conn.close();
51 } catch (JMSException e) {
52 e.printStackTrace();
53 }
54 }
55 }
56
57 public static void close(Session s){
58 if(s != null){
59 try {
60 s.close();
61 } catch (JMSException e) {
62 e.printStackTrace();
63 }
64 }
65 }
66 }
完成以上两步,就可以使用JMSUtil工具类了,我这里只是抛砖引玉,写了一小部分,其实可以封装很多方法,还请大家多多贡献。