'Design Pattern > Common' 카테고리의 다른 글

디자인 패턴(책)  (0) 2013.04.16
Programming paradigms  (0) 2013.01.01
DSL(domain-specific language)  (0) 2013.01.01
Core J2EE Patterns  (0) 2012.11.30
Rich Domain Model  (0) 2012.11.05
Posted by linuxism
,


I'm trying to implement Spring 3.1 caching as explained here and here, but it doesn't seem to be working: my method is run through every time even though it is marked @cacheable. What am I doing wrong?

I've moved it into a junit test case with its own configuration file to isolate it from the rest of my application, but the problem still happens. Here are the relevant files:

Spring-test-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:cache="http://www.springframework.org/schema/cache"
   xmlns:p="http://www.springframework.org/schema/p"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<cache:annotation-driven />

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache"/>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
      p:config-location="classpath:ehcache.xml"/>
</beans>

ehcache.xml

<ehcache>
<diskStore path="java.io.tmpdir"/>
<cache name="cache"
       maxElementsInMemory="100"
       eternal="false"
       timeToIdleSeconds="120"
       timeToLiveSeconds="120"
       overflowToDisk="true"
       maxElementsOnDisk="10000000"
       diskPersistent="false"
       diskExpiryThreadIntervalSeconds="120"
       memoryStoreEvictionPolicy="LRU"/>

</ehcache>

MyTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-test-servlet.xml"})
@Component
public class MyTest extends TestCase {

    @Test
    public void testCache1(){
        for(int i = 0; i < 5; i++){
            System.out.println("Calling someMethod...");
            System.out.println(someMethod(0));
        }
    }

    @Cacheable("testmethod")
    private int someMethod(int val){
        System.out.println("Not from cache");
        return 5;
    }
}

Relevant Pom entries: (spring-version = 3.1.1.RELEASE)

    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>

when I run the test, Spring puts out some debug messages that looks like my cache is initialized without errors

DEBUG: config.ConfigurationHelper - No CacheManagerEventListenerFactory class specified. Skipping...
DEBUG: ehcache.Cache - No BootstrapCacheLoaderFactory class specified. Skipping...
DEBUG: ehcache.Cache - CacheWriter factory not configured. Skipping...
DEBUG: config.ConfigurationHelper - No CacheExceptionHandlerFactory class specified. Skipping...
DEBUG: store.MemoryStore - Initialized net.sf.ehcache.store.MemoryStore for cache
DEBUG: disk.DiskStorageFactory - Failed to delete file cache.data
DEBUG: disk.DiskStorageFactory - Failed to delete file cache.index
DEBUG: disk.DiskStorageFactory - Matching data file missing (or empty) for index file. Deleting index file /var/folders/qg/xwdvsg6x3mx_z_rcfvq7lc0m0000gn/T/cache.index
DEBUG: disk.DiskStorageFactory - Failed to delete file cache.index
DEBUG: ehcache.Cache - Initialised cache: cache
DEBUG: config.ConfigurationHelper - CacheDecoratorFactory not configured. Skipping for 'cache'.
DEBUG: config.ConfigurationHelper - CacheDecoratorFactory not configured for defaultCache. Skipping for 'cache'.

but the debug output shows no cache checks between method calls to someMethod and the print statement from inside someMethod prints every time.

Is there something I'm missing?

share|improve this question
add comment (requires an account with 50 reputation)

From http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/cache.html

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target objectwill not lead to an actual caching at runtime even if the invoked method is marked with @Cacheable - considering using the aspectj mode in this case.

and

Method visibility and @Cacheable/@CachePut/@CacheEvict

When using proxies, you should apply the @Cache* annotations only to methods with public visibility.

  1. You self-invoke someMethod in the same target object.
  2. Your @Cacheable method is not public.
share|improve this answer
In addition to this, you'll need to extract to an Interface so Spring can dynamically write a wrapper to your class.– RockMeetHardplace May 10 '12 at 1:01


출처 - http://stackoverflow.com/questions/10343885/spring-3-1-cacheable-method-still-executed





Posted by linuxism
,


  • Reference > 
  • Query, Update and Projection Operators

Query, Update and Projection Operators

Query Selectors

Comparison

NameDescription
$allMatches arrays that contain all elements specified in the query.
$gtMatches values that are greater than the value specified in the query.
$gteMatches values that are equal to or greater than the value specified in the query.
$inMatches any of the values that exist in an array specified in the query.
$ltMatches values that are less than the value specified in the query.
$lteMatches values that are less than or equal to the value specified in the query.
$neMatches all values that are not equal to the value specified in the query.
$ninMatches values that do not exist in an array specified to the query.

Logical

NameDescription
$orJoins query clauses with a logical OR returns all documents that match the conditions of either clause.
$andJoins query clauses with a logical AND returns all documents that match the conditions of both clauses.
$notInverts the effect of a query expression and returns documents that do not match the query expression.
$norJoins query clauses with a logical NOR returns all documents that fail to match both clauses.

Element

NameDescription
$existsMatches documents that have the specified field.
$modPerforms a modulo operation on the value of a field and selects documents with a specified result.
$typeSelects documents if a field is of the specified type.

JavaScript

NameDescription
$whereMatches documents that satisfy a JavaScript expression.
$regexSelects documents where values match a specified regular expression.

Geospatial

NameDescription
$geoWithinSelects geometries within a bounding GeoJSON geometry.
$geoIntersectsSelects geometries that intersect with a GeoJSON geometry.
$nearReturns geospatial objects in proximity to a point.
$nearSphereReturns geospatial objects in proximity to a point on a sphere.

Array

NameDescription
$elemMatchSelects documents if element in the array field matches all the specified $elemMatchcondition.
$sizeSelects documents if the array field is a specified size.

Update Operators

Fields

NameDescription
$incIncrements the value of the field by the specified amount.
$renameRenames a field.
$setOnInsertSets the value of a field upon documentation creation during an upsert. Has no effect on update operations that modify existing documents.
$setSets the value of a field in an existing document.
$unsetRemoves the specified field from an existing document.

Array

Operators

NameDescription
$Acts as a placeholder to update the first element that matches the query condition in an update.
$addToSetAdds elements to an existing array only if they do not already exist in the set.
$popRemoves the first or last item of an array.
$pullAllRemoves multiple values from an array.
$pullRemoves items from an array that match a query statement.
$pushAllDeprecated. Adds several items to an array.
$pushAdds an item to an array.

Modifiers

NameDescription
$eachModifies the $push and $addToSet operators to append multiple items for array updates.
$sliceModifies the $push operator to limit the size of updated arrays.
$sortModifies the $push operator to reorder documents stored in an array.

Bitwise

NameDescription
$bitPerforms bitwise AND and OR updates of integer values.

Isolation

NameDescription
$isolatedModifies behavior of multi-updates to improve the isolation of the operation.

Projection Operators

NameDescription
$Projects the first element in an array that matches the query condition.
$elemMatchProjects only the first element from an array that matches the specified $elemMatchcondition.
$sliceLimits the number of elements projected from an array. Supports skip and limit slices.

Meta-Query Operators

Query Modifiers

NameDescription
$commentAdds a comment to the query to identify queries in the database profiler output.
$explainForces MongoDB to report on query execution plans. See explain().
$hintForces MongoDB to use a specific index. See hint()
$maxScanLimits the number of documents a cursor will return for a query. See limit().
$maxSpecifies a minimum exclusive upper limit for the index to use in a query. See max().
$minSpecifies a minimum inclusive lower limit for the index to use in a query. See min().
$orderbyReturns a cursor with documents sorted according to a sort specification. See sort().
$returnKeyForces the cursor to only return fields included in the index.
$showDiskLocModifies the documents returned to include references to the on-disk location of each document.
$snapshotForces the query to use the index on the _id field. See snapshot().

Sort Order Specifier

NameDescription
$naturalA special sort order that orders documents using the order of documents on disk.


    출처 - http://docs.mongodb.org/manual/reference/operator/






    'DB > MongoDB' 카테고리의 다른 글

    mongo - TTL  (0) 2014.01.15
    mongodb - 콜렉션 필드 형변환 (How to change the type of a field)  (0) 2013.10.07
    mongodb - GridFS  (0) 2013.06.18
    mongodb - binary data(type) 저장  (0) 2013.06.18
    mongodb - BSON(Binary JSON)  (0) 2013.06.18
    Posted by linuxism
    ,