执行器模式设计和使用
2017-09-14 15:33
141 查看
1.定义: @Autowired private JedisPool jedisPool; public static interface Execution { public <T> T process(Jedis jedis); } /** * 执行请求,开始前获取资源,结束后返回资源 * * @param execution * @return */ public <T> T execute(Execution execution) { Jedis jedis = null; try { jedis = jedisPool.getResource(); T result = execution.process(jedis); return result; } catch (JedisConnectionException e) { throw e; } finally { if (null != jedis) { jedis.close(); } } } 2.使用: @Autowired private JedisExecutionService jedisExecutionService; public void set(final String key, final Object value, final int seconds) { if (null == key) { throw new IllegalArgumentException("Cached key cannot be null."); } if (null == value) { throw new IllegalArgumentException("Cached value cannot be null."); } jedisExecutionService.execute(new Execution() { @Override public Object process(Jedis jedis) { byte[] byteArray = serialize(value); jedis.set(key.getBytes(), byteArray); if (seconds > 0) { jedis.expire(key.getBytes(), seconds); } return null; } }); } public void expire(final String key, final int seconds) { if (null == key) { throw new IllegalArgumentException("Cached key cannot be null."); } jedisExecutionService.execute(new Execution() { @Override public Object process(Jedis jedis) { jedis.expire(key.getBytes(), seconds); return null; } }); } public Object get(final String key) { if (null == key) { throw new IllegalArgumentException("Cached key cannot be null."); } return jedisExecutionService.execute(new Execution() { @Override public Object process(Jedis jedis) { byte[] bs = jedis.get(key.getBytes()); if (null == bs) { return null; } else { return deserialize(bs); } } }); }
相关文章推荐
- 使用Publish/Subscribe 设计模式达到对象间数据同步
- 使用设计模式构建通用数据库访问类
- 使用设计模式构建通用数据库访问类
- 设计模式-旧话重提之类工厂的使用
- 使用设计模式构建通用数据库访问类
- 设计模式-旧话重提之类工厂的使用
- 使用设计模式改善程序结构(2)
- 使用设计模式改善程序结构(一)
- 使用设计模式构建通用数据库访问类(转自天极)
- 使用设计模式改善程序结构(三)
- 与Erich Gamma的一次谈话(第一部分) - 如何使用设计模式 (zt)
- 将多种设计模式结合使用
- 如何将多种设计模式结合使用(有原代码)
- 使用设计模式构建通用数据库访问类
- [转贴] 不要以为使用了模式就是好设计
- 《C# 设计模式》笔记: 第4章 在C#中使用类和对象
- 使用Publish/Subscribe 设计模式达到对象间数据同步(二)
- 使用设计模式改善程序结构(二)
- Henry手记—使用Template Method设计模式的.NET事件处理机制(一)
- 使用设计模式改善程序结构