Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Java [игнор отключен] [закрыт для гостей] / ejb3, Interceptors, ehcache / 1 сообщений из 1, страница 1 из 1
30.10.2012, 13:54:13
    #38018616
breath
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
ejb3, Interceptors, ehcache
есть restful вебсервисы,(по сути те же сервлеты), построенны на jersey, кусок из web.xml

<servlet>
<servlet-name>RESTful</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

на нужных методах висит интерсептор CacheController, перехватываем, проверяем если в кеше, если есть отдаем ответ и прерываем выполнение метода, если нет - продолжаем метод, кладем в кеш данные.

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
@Path("document")
@Stateless
public class DocumentService {
private Cached cached;

  @PostConstruct
  private void init() {
    cached = (Cached) ctx.lookup(EJB_PATH + Cached.class.getSimpleName());
  }

  @GET
  @Path("path")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  @Interceptors({ResponseHeader.class, CacheController.class})
  public Response getData(int id){
     ....
      data = DB.getData(id);
     getCached().putValue(data);
      return Response.....
  }
}



класс CacheController

Код: java
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.
public class CacheController<V> {

  @AroundInvoke
  public Object checkCache(InvocationContext context) throws Exception {
    BaseHttpService service = (BaseHttpService) context.getTarget();
    Object[] objects = context.getParameters();
    StringBuilder methodParamsValue = new StringBuilder();
    if (null != objects && objects.length > 0) {
      for (Object object : objects) {
        methodParamsValue.append(object);
      }
    }
    StringBuilder cacheElementKey = new StringBuilder().append(service.getClass().getSimpleName()).append(context.getMethod().getName()).append(methodParamsValue.toString()).append(service.getSession().getSessionId());
    int hashKey = cacheElementKey.toString().hashCode();
    V value;
    if ((value = service.getCached().getObjectValue(hashKey)) != null) {
      Logger.getLogger(service.getClass().getSimpleName()).log(Level.SEVERE, "((((cache " + hashKey);
      if (context.getMethod().getReturnType().getSimpleName().equals(Response.class.getSimpleName())) {
        return service.getResponseStatusOK(service.toJson(value));
      } else {
        return service.toJson(value);
      }
    } else {
      service.getCached().setCacheElementKey(hashKey);
      return context.proceed();
    }
  }
}



класс Cached, тоже ejb stateless бин(singleton тоже пробовал), для кеша используется ehcache, ключем служат передаваемые методу параметры, имя метода

Код: java
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.
@Stateless
@Startup
public class Cached {
  public final static String EJB_CACHE = "ejbCache";
  private CacheManager cacheManager;
  @Setter @Getter private int cacheElementKey = -1;

  @PostConstruct
  private void init() {
    cacheManager = CacheManager.create();
    Cache ejbCache = new Cache(new CacheConfiguration(EJB_CACHE, 10000)
            .eternal(false)
            .timeToLiveSeconds(40)
            .timeToIdleSeconds(30));
    cacheManager.addCacheIfAbsent(ejbCache);
  }

  @PreDestroy
  private void destroy() {
    cacheManager.shutdown();
  }

  public <V> boolean putValue(V v) {
    if (-1 != cacheElementKey) {
      int tK = cacheElementKey;
      cacheElementKey = -1;
      return (null != v && !(v instanceof List) || v instanceof List && ((List) v).size() > 0) && putValue(tK, v);
    }
    return false;
  }

  public <K, V> boolean putValue(K k, V v) {
    boolean ret = false;
    try {
      cacheManager.getCache(EJB_CACHE).put(new Element(k, v));
      ret = true;
    } catch (IllegalArgumentException | IllegalStateException | CacheException e) {
      Logger.getLogger(Cached.class.getName()).log(Level.SEVERE, "putValue:", e);
    }
    return ret;
  }

  public <K, V> V getObjectValue(K k) {
    //Logger.getLogger(Cached.class.getName()).log(Level.SEVERE, "!!!!!:" + ejbCache.getSize());
    Element element;
    if ((element = cacheManager.getCache(EJB_CACHE).get(k)) != null) {
      return (V) element.getObjectValue();
    }
    return null;
  }

  public <K, V> V getValue(K k) {
    Element element;
    if ((element = cacheManager.getCache(EJB_CACHE).get(k)) != null) {
      return (V) element.getValue();
    }
    return null;
  }
}



когда делаем запросы из браузера по одну, все ок.
как начинаем тестировать тестами, много запросов и тд.. то бывает кеш отдает не данные вызванного сейчас метода, а какие то другие закешированные ранее, или ключ старый используется или что то еще, вот это и не понятно.
...
Рейтинг: 0 / 0
Форумы / Java [игнор отключен] [закрыт для гостей] / ejb3, Interceptors, ehcache / 1 сообщений из 1, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]