最近在使用spring-data-redis的redisTemplate,所以写篇使用记录吧。

  1.不用多说,使用maven引入相关依赖,因为项目已经引入其他的

  

<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配置文件

<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>

  假如要使用redis驱动lua脚本则需要加入类似的配置

<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脚本文件(updateAvailableSavingsCard.lua)

-- 操作可用储蓄卡,当客户购买则减,卖家增加可用库存则加,使用lua脚本redis操作的保证原子性
redis.call('INCRBY', KEYS[], ARGV[])
local current = redis.call('GET', KEYS[])
local result ={}
result["@class"] = "org.meibaobao.ecos.basecomponent.common.Result"
if tonumber(current)<
then
redis.call('DECRBY', KEYS[], ARGV[])
current = redis.call('GET', KEYS[])
result["success"] = false
result["data"] = current
local encodestr = cjson.encode(result)
print(encodestr)
return encodestr
end
result["success"] = true
result["data"] = current
local encodestr = cjson.encode(result)
print(encodestr)
return encodestr

3.资源文件

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

4.java代码

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; /**
* 储蓄卡资源
*
*/
@Service
public class StoredCardInventoryServiceImpl {
@Resource(name = "updateAvailableSavingsCard")
RedisScript<Result> updateAvailableSavingsCard;
@Resource(name = "initAvailableSavingsCard")
RedisScript<Boolean> initAvailableSavingsCard; @Autowired
RedisTemplate<String,Integer> redisTemplate; public static String availableStotredCardInventoryNamePre = "availableStotredCard_";
/**
* 操作可用资源
*/
public Result availableStotredCardInventory(String storedCardSchemeNo,int num){
return redisTemplate.execute(updateAvailableSavingsCard, Collections.singletonList(availableStotredCardInventoryNamePre+storedCardSchemeNo),num);
}
/**
* 初始化可用资源
*/
public Boolean initAvailableStotredCardInventory(String storedCardSchemeNo,int num){
return redisTemplate.execute(initAvailableSavingsCard, Collections.singletonList(availableStotredCardInventoryNamePre+storedCardSchemeNo),
num);
}
}

5.junit4单元测试代码

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.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:development/xml/spring/applicationContext.xml" })
public class StotredCardInventoryServiceImplTest { @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")); //测试hash
String key = "hashtest11";
redisTemplate.opsForHash().put(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));
}
}
} }

redisTemplate的spring配置以及lua脚本驱动的更多相关文章

  1. 【spring boot】【redis】spring boot基于redis的LUA脚本 实现分布式锁

    spring boot基于redis的LUA脚本 实现分布式锁[都是基于redis单点下] 一.spring boot 1.5.X 基于redis 的 lua脚本实现分布式锁 1.pom.xml &l ...

  2. Spring RedisTemplate操作-xml配置(1)

    网上没能找到全的spring redistemplate操作例子,故特意化了点时间做了接口调用练习,基本包含了所有redistemplate方法. 该操作例子是个系列,该片为spring xml配置, ...

  3. SpringBoot通过RedisTemplate执行Lua脚本

    如果你对Redis和Lua的关系不太清楚,请先阅读:Redis进阶之使用Lua脚本开发 1.RedisScript 首先你得引入spring-boot-starter-data-redis依赖,其次把 ...

  4. 在Spring中使用Redis Lua脚本批量删除缓存

    背景 之前分享了一篇利用lua脚本批量删除redis的key的文章.现在项目中我打算使用spring的缓存,而Spring缓存以前我是用ehcache来做实现的.没发现什么问题..这次我换成redis ...

  5. spring boot 中使用LUA脚本

    编写LUA脚本 该脚本功能:先检查redis中某个key的值是否与期望的值V1一致,如果一致则将其修改为新的值V2并返回true,否则返回false.其实就是CAS. local current = ...

  6. redis原子性读写操作之LUA脚本和watch机制

    最近在开发电商平台的子系统--储值卡系统,系统核心业务涉及到金额消费以及库存控制,因此为了解决建立在内存上高并发情况下的事务控制,使用了spring封装的RedisTemplate执行lua脚本进行原 ...

  7. Lua脚本在redis分布式锁场景的运用

    目录 锁和分布式锁 锁是什么? 为什么需要锁? Java中的锁 分布式锁 redis 如何实现加锁 锁超时 retry redis 如何释放锁 不该释放的锁 通过Lua脚本实现锁释放 用redis做分 ...

  8. redis集群+JedisCluster+lua脚本实现分布式锁(转)

    https://blog.csdn.net/qq_20597727/article/details/85235602 在这片文章中,使用Jedis clien进行lua脚本的相关操作,同时也使用一部分 ...

  9. spring boot:redis+lua实现生产环境中可用的秒杀功能(spring boot 2.2.0)

    一,秒杀需要具备的功能: 秒杀通常是电商中用到的吸引流量的促销活动方式 搭建秒杀系统,需要具备以下几点: 1,限制每个用户购买的商品数量,(秒杀价格为吸引流量一般会订的很低,不能让一个用户全部抢购到手 ...

随机推荐

  1. (备忘)自定义viewgroup与点击分发事件

    public class ScoreButton extends ViewGroup 在类中重写onTouchEvent方法 @Override public boolean onTouchEvent ...

  2. php 批量去空格和注释

    原理:php自带函数去注释和空格  => php_strip_whitespace如题,新建文件 re_note.php,将文件放入你要批量去除注释和空格的根目录.然后运行就行了 代码如下: & ...

  3. 去掉UITableView多余的空白行分割线

    一.问题描述 在学习和开发中经常会遇到下面的问题,UITableView的UITableViewCell很少或者没有时,但UITableView有很多的空白行分割线.如下图: 如何去掉UITableV ...

  4. Spring Security控制权限

    Spring Security控制权限 1,配置过滤器 为了在项目中使用Spring Security控制权限,首先要在web.xml中配置过滤器,这样我们就可以控制对这个项目的每个请求了. < ...

  5. iOS开发UI篇—核心动画(关键帧动画)

    转自:http://www.cnblogs.com/wendingding/p/3801330.html iOS开发UI篇—核心动画(关键帧动画) 一.简单介绍 是CApropertyAnimatio ...

  6. HTML:让表单、文本框只读,不可编辑的方法

    有时候,我们希望表单中的文本框是只读的,让用户不能修改其中的信息,如使<input type="text" name="input1" value=&qu ...

  7. 如何使用Python在Kaggle竞赛中成为Top15

    如何使用Python在Kaggle竞赛中成为Top15 Kaggle比赛是一个学习数据科学和投资时间的非常的方式,我自己通过Kaggle学习到了很多数据科学的概念和思想,在我学习编程之后的几个月就开始 ...

  8. 【leetcode】Factorial Trailing Zeroes

    题目描述: Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be ...

  9. 简述抽象和封装,对你学习Java有一些作用

    作为一个Java 初学者,对Java的理解可能有些片面,甚至有些错误的理解,对于观看此处的您,希望您选择性观看!!! 天知道我为什么选择学习编程,我不爱编程,但是我既然学习了,还是会努力学习的,在此分 ...

  10. [leetcode] 题型整理之数字加减乘除乘方开根号组合数计算取余

    需要注意overflow,特别是Integer.MIN_VALUE这个数字. 需要掌握二分法. 不用除法的除法,分而治之的乘方 2. Add Two Numbers You are given two ...