Spring configuration of redisTemplate and lua Script driver, redistemplatelua

Source: Internet
Author: User

Spring configuration of redisTemplate and lua Script driver, redistemplatelua

I recently used spring-data-redis redisTemplate, so write a usage record.

1. Needless to say, use maven to introduce related dependencies because the project has introduced other

  

<dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-redis</artifactId>            <version>1.6.2.RELEASE</version>            <exclusions>                <exclusion>                    <artifactId>spring-context</artifactId>                    <groupId>org.springframework</groupId>                </exclusion>                <exclusion>                    <artifactId>spring-aop</artifactId>                    <groupId>org.springframework</groupId>                </exclusion>                <exclusion>                    <artifactId>spring-context-support</artifactId>                    <groupId>org.springframework</groupId>                </exclusion>                <exclusion>                    <artifactId>spring-tx</artifactId>                    <groupId>org.springframework</groupId>                </exclusion>                <exclusion>                    <artifactId>spring-core</artifactId>                    <groupId>org.springframework</groupId>                </exclusion>                <exclusion>                    <artifactId>slf4j-api</artifactId>                    <groupId>org.slf4j</groupId>                </exclusion>            </exclusions>        </dependency>

2. spring configuration file

<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">          <property name="maxIdle" value="${redis.maxIdle}" />          <property name="maxActive" value="${redis.maxActive}" />          <property name="maxWait" value="${redis.maxWait}" />          <property name="testOnBorrow" value="${redis.testOnBorrow}" />    </bean>    <!-- Jedis ConnectionFactory -->    <bean id="jedisConnectionFactory"        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"        p:hostName="${redis.url}" p:port="${redis.port}" p:password="${redis.password}" p:pool-config-ref="poolConfig"/>    <bean id="stringRedisSerializer"        class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>    <bean id="jsonSerializer"        class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer">    </bean>    <!-- redis template definition -->    <bean id="redisTemplate" name="redisTemplate"        class="org.springframework.data.redis.core.RedisTemplate"        p:connection-factory-ref="jedisConnectionFactory" p:keySerializer-ref="stringRedisSerializer"        p:hashKeySerializer-ref="stringRedisSerializer" p:valueSerializer-ref="jsonSerializer"        p:hashValueSerializer-ref="jsonSerializer">    </bean>

If you want to use the redis drive lua script, you need to add similar configurations.

<bean id="updateAvailableSavingsCard" class="org.springframework.data.redis.core.script.DefaultRedisScript">        <property name="location" value="classpath:META-INF/lua/updateAvailableSavingsCard.lua"/>        <property name="resultType" value="org.meibaobao.ecos.basecomponent.common.Result"/>    </bean>    <bean id="initAvailableSavingsCard" class="org.springframework.data.redis.core.script.DefaultRedisScript">        <property name="location" value="classpath:META-INF/lua/initAvailableSavingsCard.lua"/>        <property name="resultType" value="java.lang.Boolean"/>    </bean>

Lua script file (updateAvailableSavingsCard. lua)

-- The operation can be performed on the debit card. When the customer buys the deposit, the seller adds the available inventory, and the lua script redis is used to ensure the atomic redis operation. call ('encrby', KEYS [1], ARGV [1]) local current = redis. call ('get', KEYS [1]) local result = {} result ["@ class"] = "org. meibaobao. ecos. basecomponent. common. result "if tonumber (current) <0 then redis. call ('describy', KEYS [1], ARGV [1]) current = redis. call ('get', KEYS [1]) result ["success"] = false result ["data"] = current local encodestr = cjson. encode (result) print (encodestr) return encodestrendresult ["success"] = trueresult ["data"] = currentlocal encodestr = cjson. encode (result) print (encodestr) return encodestr

 

3. Resource file

#redisredis.url=10.72.82.124redis.port=6379redis.password=redis.maxIdle=200redis.maxActive=1024redis.maxWait=1000redis.testOnBorrow=true

4. java code

Package org. meibaobao. ecos. storedCard. scheme. service. component. impl; import java. util. collections; import javax. annotation. resource; import org. meibaobao. ecos. basecomponent. common. result; import org. springframework. beans. factory. annotation. autowired; import org. springframework. data. redis. core. redisTemplate; import org. springframework. data. redis. core. script. redisScript; import org. springframework. stereotype. service;/*** debit card resources **/@ Servicepublic class StoredCardInventoryServiceImpl {@ Resource (name = "updateAvailableSavingsCard") RedisScript <Result> updateAvailableSavingsCard; @ Resource (name = "canonical ") redisScript <Boolean> initAvailableSavingsCard; @ Autowired RedisTemplate <String, Integer> redisTemplate; public static String availableStotredCardInventoryNamePre = "availableStotredCard _"; /*** operation available resources */public Result availableStotredCardInventory (String storedCardSchemeNo, int num) {return redisTemplate.exe cute (updateAvailableSavingsCard, Collections. singletonList (Bytes + storedCardSchemeNo), num);}/*** initialize available resources */public Boolean values (String storedCardSchemeNo, int num) {return redisTemplate.exe cute (initAvailableSavingsCard, colleard. singletonList (availableStotredCardInventoryNamePre + storedCardSchemeNo), num );}}

5. junit4 unit test code

Package org. meibaobao. ecos. storedCard. scheme. service. component. impl; import java. util. map; import javax. annotation. resource; import org. junit. test; import org. junit. runner. runWith; import org. springframework. beans. factory. annotation. autowired; import org. springframework. data. redis. core. redisTemplate; import org. springframework. test. context. contextConfiguration; import org. springframework. test. context. junit 4. springJUnit4ClassRunner; @ RunWith (SpringJUnit4ClassRunner. class) @ ContextConfiguration (locations = {"classpath: development/xml/spring/applicationContext. xml "}) public class implements {@ Resource private StoredCardInventoryServiceImpl stotredCardInventoryServiceImpl; @ Autowired RedisTemplate <String, Object> redisTemplate; @ Test public void availableStotredCardInventory (){ System. out. println (stotredCardInventoryServiceImpl. initAvailableStotredCardInventory ("test1111112",-10); System. out. println (stotredCardInventoryServiceImpl. initAvailableStotredCardInventory ("test1111112",-10); redisTemplate. opsForValue (). set ("test99999", "123asd"); System. out. println (redisTemplate. opsForValue (). get ("test99999"); // test hash String key = "hashtest11"; redisTemplate. opsForHash (). pu T (key, "name1", "11"); redisTemplate. opsForHash (). put (key, "name2", "22"); redisTemplate. opsForHash (). put (key, "name3", "33"); System. out. println (redisTemplate. opsForHash (). get (key, "name2"); redisTemplate. opsForHash (). delete (key, "name2"); System. out. println (redisTemplate. opsForHash (). get (key, "name2"); System. out. println (redisTemplate. opsForHash (). get (key, "name1"); Map <Object, Object> opsMap = RedisTemplate. opsForHash (). entries (key); if (opsMap! = Null) {System. out. println (opsMap. keySet (); System. out. println (opsMap. values (); for (Object object: opsMap. keySet () {System. out. println (object + "," + opsMap. get (object ));}}}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.