1 PackageCom.devpg.redis;2 3 ImportOrg.junit.After;4 ImportOrg.junit.Assert;5 Importorg.junit.Test;6 ImportOrg.junit.runner.RunWith;7 ImportOrg.slf4j.Logger;8 Importorg.slf4j.LoggerFactory;9 Importorg.springframework.beans.factory.annotation.Autowired;Ten Importorg.springframework.dao.DataAccessException; One Importorg.springframework.data.redis.core.RedisOperations; A Importorg.springframework.data.redis.core.RedisTemplate; - ImportOrg.springframework.data.redis.core.SessionCallback; - Importorg.springframework.test.context.ContextConfiguration; the ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith (Springjunit4classrunner.class) -@ContextConfiguration (locations = {"/testcontext.xml") }) + Public classTransactiontest { - +Logger Logger = Loggerfactory.getlogger (transactiontest.class); A at @Autowired -Redistemplate<string, integer>template; - - Private FinalString key = "Tx-key"; - - @After in Public voidDeletecounter () { - Template.delete (key); to } + - @Test the Public voiduseoptimisticlocking () { * Final intValuesetinbetween = 23; $ Final intValuesetwithinsession = 42;Panax Notoginseng - /* the * By default all template method call creates a new connection-so + * WATCH, Mutli, EXEC, Unwatch won ' t work because of the missing A * Context. to do use of transaction support use Sessioncallback which the * reuses the underlying connection. + */ -Template.execute (NewSessioncallback<void>() { $ $ @Override - PublicVoid Execute (redisoperations operations) - throwsDataAccessException { the Operations.watch (key); - Wuyi setkeybyotherbysession (valuesetinbetween); the - Operations.multi (); Wu Operations.boundvalueops (Key). Set (valuesetwithinsession); - operations.exec (); About $ return NULL; - } - }); - A intValue =Template.boundvalueops (key). Get (). Intvalue (); + assert.assertequals (Valuesetinbetween, value); the } - $ Private Final voidSetkeybyotherbysession (intvalue) { the Template.boundvalueops (Key). Set (value); the } the}
The key moment is to find Google: https://github.com/devpg/spring-data-redis-example/blob/master/src/test/java/com/devpg/redis/ Transactiontest.java
This is the main sentence.
/* * By default all template method call creates a new connection-so * WATCH, Mutli, EXEC, Unwatch won ' t work Because of the missing * context. To do use of transaction support use Sessioncallback which * reuses the underlying connection. */
Spring Data Redis Watch transaction does not perform a problem