redisTemplate的spring配置以及lua脚本驱动
最近在使用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脚本驱动的更多相关文章
- 【spring boot】【redis】spring boot基于redis的LUA脚本 实现分布式锁
spring boot基于redis的LUA脚本 实现分布式锁[都是基于redis单点下] 一.spring boot 1.5.X 基于redis 的 lua脚本实现分布式锁 1.pom.xml &l ...
- Spring RedisTemplate操作-xml配置(1)
网上没能找到全的spring redistemplate操作例子,故特意化了点时间做了接口调用练习,基本包含了所有redistemplate方法. 该操作例子是个系列,该片为spring xml配置, ...
- SpringBoot通过RedisTemplate执行Lua脚本
如果你对Redis和Lua的关系不太清楚,请先阅读:Redis进阶之使用Lua脚本开发 1.RedisScript 首先你得引入spring-boot-starter-data-redis依赖,其次把 ...
- 在Spring中使用Redis Lua脚本批量删除缓存
背景 之前分享了一篇利用lua脚本批量删除redis的key的文章.现在项目中我打算使用spring的缓存,而Spring缓存以前我是用ehcache来做实现的.没发现什么问题..这次我换成redis ...
- spring boot 中使用LUA脚本
编写LUA脚本 该脚本功能:先检查redis中某个key的值是否与期望的值V1一致,如果一致则将其修改为新的值V2并返回true,否则返回false.其实就是CAS. local current = ...
- redis原子性读写操作之LUA脚本和watch机制
最近在开发电商平台的子系统--储值卡系统,系统核心业务涉及到金额消费以及库存控制,因此为了解决建立在内存上高并发情况下的事务控制,使用了spring封装的RedisTemplate执行lua脚本进行原 ...
- Lua脚本在redis分布式锁场景的运用
目录 锁和分布式锁 锁是什么? 为什么需要锁? Java中的锁 分布式锁 redis 如何实现加锁 锁超时 retry redis 如何释放锁 不该释放的锁 通过Lua脚本实现锁释放 用redis做分 ...
- redis集群+JedisCluster+lua脚本实现分布式锁(转)
https://blog.csdn.net/qq_20597727/article/details/85235602 在这片文章中,使用Jedis clien进行lua脚本的相关操作,同时也使用一部分 ...
- spring boot:redis+lua实现生产环境中可用的秒杀功能(spring boot 2.2.0)
一,秒杀需要具备的功能: 秒杀通常是电商中用到的吸引流量的促销活动方式 搭建秒杀系统,需要具备以下几点: 1,限制每个用户购买的商品数量,(秒杀价格为吸引流量一般会订的很低,不能让一个用户全部抢购到手 ...
随机推荐
- [BZOJ3173][Tjoi2013]最长上升子序列
[BZOJ3173][Tjoi2013]最长上升子序列 试题描述 给定一个序列,初始为空.现在我们将1到N的数字插入到序列中,每次将一个数字插入到一个特定的位置.每插入一个数字,我们都想知道此时最长上 ...
- JS常见错误和分析
列举一些在前端开发中遇到的一些错误信息和解决办法 错误信息 解决办法 Uncaught SyntaxError: Unexpected token o 使传入的字符串不是符合严格的JSON格式会抛出异 ...
- linux 命令笔记
linux 命令 创建目录 mkdir XX 列出目录 ls 进入目录 cd .. 进入上层目录 cd xx 进入xx目录 cd ~ 进入用户主目录 删除目录 rm -fr XX 清空目录,谨慎使用 ...
- Odoo中最小库存规则和按订单生成规则的区别
---恢复内容开始--- 最小库存规则(Minimum stock rule)用来保证你的库存产品数量总是不会低于设定的最小库存数量.用来保证产品生产和回到客户的需求.当库存产品低于这个最小库存数量时 ...
- Document对象和window对象
window对象--- 代表浏览器中的一个打开的窗口或者框架,window对象会在<body>或者<frameset>每次出现时被自动创建,在客户端JavaScript中,Wi ...
- 数据库DBA(3年以内需求)
1.DBA工作:日常维护,备份及恢复,系统安装,补丁应用,健康检查及优化,故障处理; 2.精通sql语句.视图存储过程.函数的编写.触发器; 3.精通data guard/RAC,能顺利配置和管理da ...
- string与wstring之间的转换
#include <string>std::string ws2s(const std::wstring& ws){ std::string curLocale = setl ...
- 解决java.lang.InstantiationError: sun.net.ftp.FtpClient
换用jdk1.6 .如果是放容器里的,也把容器的jdk换成1.6
- PHP字符串函数
php字符串处理函数大全 addcslashes — 为字符串里面的部分字符添加反斜线转义字符addslashes — 用指定的方式对字符串里面的字符进行转义bin2hex — 将二进制数据转换成十六 ...
- Redis相关
Redis 持久化 1 why 数据需要持久化,当内存数据库使用的情况 防止缓存失效时候的雪崩效应 2 how 两种方式,快照和日志(aof)方式,各有优缺点. Redis的缓存失效策略 1 what ...