Java Cache Tutorial with Method Annotations (CDI)
From Resin 4.0 Wiki
(Difference between revisions)
(Created page with "{{Caching}} {{Cookbook}} Faster application performance is possible with Java caching by saving the results of long calculations and reducing database load. The Java caching ...") |
|||
Line 1: | Line 1: | ||
{{Caching}} {{Cookbook}} | {{Caching}} {{Cookbook}} | ||
− | + | Java caching can speed application performance and lower database load by annotating cacheable methods. The Java caching API (JCache) includes standard | |
− | + | method annotations that let you add caching just by annotating your methods. Assuming your bean is a Java Dependency Injection (CDI) bean, your method will | |
− | + | be cached automatically. When using an application server like the Resin application server that supports both CDI and JCache, you can add caching easily | |
+ | without much configuration. | ||
+ | You'll want to cache to | ||
* Improve latency | * Improve latency | ||
* Reduce database load | * Reduce database load | ||
* Reduce CPU use | * Reduce CPU use | ||
+ | |||
+ | With the caching annotations, you can add caching with the following two steps: | ||
# Add a @CacheResult annotation to the method you want to cache | # Add a @CacheResult annotation to the method you want to cache | ||
# Use Java Dependency Injection (CDI) to get the bean | # Use Java Dependency Injection (CDI) to get the bean | ||
+ | |||
+ | In the example, we'll inject the MyBean into a servlet for testing using the CDI @Inject method. | ||
=== MyBean.java === | === MyBean.java === |
Revision as of 00:00, 28 January 2012
Java caching can speed application performance and lower database load by annotating cacheable methods. The Java caching API (JCache) includes standard method annotations that let you add caching just by annotating your methods. Assuming your bean is a Java Dependency Injection (CDI) bean, your method will be cached automatically. When using an application server like the Resin application server that supports both CDI and JCache, you can add caching easily without much configuration.
You'll want to cache to
- Improve latency
- Reduce database load
- Reduce CPU use
With the caching annotations, you can add caching with the following two steps:
- Add a @CacheResult annotation to the method you want to cache
- Use Java Dependency Injection (CDI) to get the bean
In the example, we'll inject the MyBean into a servlet for testing using the CDI @Inject method.
MyBean.java
package org.example.mypkg; public class MyBean { @CacheResult String doLongOperation(String key) { ... } }
MyServlet.java
package org.example.mypkg; public class MyServlet extends GenericServlet { @Inject MyBean _bean; public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { PrintWriter out = res.getWriter(); String result = _bean.doLongOperation("test"); out.println("test: " + result); } }
WEB-INF/beans.xml
<beans/>