原文:http://chentian114.iteye.com/blog/2292323

1、通过spring-data-redis集成redis

pom.xml依赖包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.chen</groupId>
<artifactId>test_redis02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build />
<properties>
<spring.version>3.1.2.RELEASE</spring.version>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
</project>

spring application-reids.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
"> <!-- 加载配置文件 -->
<context:property-placeholder location="classpath:redis.properties"/>
<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> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean> </beans>

UserDaoImpl.java

package com.chen.dao;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository; import com.chen.pojo.User;
@Repository
public class UserDaoImpl implements UserDao { @Autowired
private RedisTemplate<Serializable,Serializable> redisTemplate; public void saveUser(final User user) {
redisTemplate.execute(new RedisCallback<Object>(){
@Override
public Object doInRedis(RedisConnection connection)
throws DataAccessException {
String str= "user.uid."+user.getId();
byte[] key = redisTemplate.getStringSerializer().serialize(str);
connection.set(key,redisTemplate.getStringSerializer().serialize(user.getName()));
return null;
}
});
} public User getUser(final long id) {
return redisTemplate.execute(new RedisCallback<User>(){
@Override
public User doInRedis(RedisConnection connection) throws DataAccessException {
byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);
if(connection.exists(key)) {
byte[] value = connection.get(key);
String name = redisTemplate.getStringSerializer().deserialize(value);
User user = new User();
user.setName(name);
user.setId(id);
return user;
}
return null;
}
});
} }

2、通过jedis集成redis

spring applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
"> <!-- 加载配置文件 -->
<context:property-placeholder location="classpath:redis.properties"/>
<bean id="jedisPoolConfig" 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>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port}" />
<!-- <constructor-arg name="timeout" value="${redis.timeout}" /> -->
</bean>
</list>
</constructor-arg>
</bean> </beans>

RedisDataSourceImpl.java

package com.chen.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
@Repository("redisDataSource")
public class RedisDataSourceImpl implements RedisDataSource { @Autowired
private ShardedJedisPool shardedJedisPool; public ShardedJedis getRedisClient() {
try{
ShardedJedis shardJedis = shardedJedisPool.getResource();
return shardJedis;
}catch(Exception e){
e.printStackTrace();
}
return null;
} public void returnResource(ShardedJedis shardedJedis) {
shardedJedisPool.returnResource(shardedJedis);
} public void returnResource(ShardedJedis shardedJedis, boolean broken) {
if(broken){
shardedJedisPool.returnBrokenResource(shardedJedis);
}else{
shardedJedisPool.returnResource(shardedJedis);
}
} }

RedisClientTemplate.java

package com.chen.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import redis.clients.jedis.ShardedJedis; @Repository("redisClientTemplate")
public class RedisClientTemplate {
@Autowired
private RedisDataSource redisDataSource; public void disconnect(){
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
shardedJedis.disconnect();
} public String set(String key,String val){
String result = null ;
ShardedJedis jedis = redisDataSource.getRedisClient();
if(jedis ==null)return null;
boolean broken = false;
try{
result = jedis.set(key, val);
}catch(Exception e){
e.printStackTrace();
broken = true ;
}finally{
redisDataSource.returnResource(jedis,broken);
}
return result;
} public String get(String key){
String result = null;
ShardedJedis jedis = redisDataSource.getRedisClient();
if(jedis==null)return result;
boolean broken = false;
try{
result = jedis.get(key);
}catch(Exception e){
e.printStackTrace();
broken= true;
}finally{
redisDataSource.returnResource(jedis,broken);
}
return result;
}
}

DemoTest.java

spring集成redis,集成redis集群的更多相关文章

  1. Redis+Twemproxy+HAProxy集群(转) 干货

    原文地址:Redis+Twemproxy+HAProxy集群  干货 Redis主从模式 Redis数据库与传统数据库属于并行关系,也就是说传统的关系型数据库保存的是结构化数据,而Redis保存的是一 ...

  2. redis:哨兵集群配置

    最少配置1主2从3哨兵 一.引言 上一篇文章我们详细的讲解了Redis的主从集群模式,其实这个集群模式配置很简单,只需要在Slave的节点上进行配置,Master主节点的配置不需要做任何更改,但是有一 ...

  3. Redis 高可用集群

    Redis 高可用集群 Redis 的集群主从模型是一种高可用的集群架构.本章主要内容有:高可用集群的搭建,Jedis连接集群,新增集群节点,删除集群节点,其他配置补充说明. 高可用集群搭建 集群(c ...

  4. Redis存储Tomcat集群的Session

    Redis存储Tomcat集群的Session 如何 做到把新开发的代码推送到到生产系统中部署,生产系统要能够零宕机.对使用用户零影响. 设想 是使用集群来搞定,通过通知负载均衡Nginx,取下集群中 ...

  5. Redis 3.0 集群搭建

    Redis 3.0 集群搭建 开启两个虚拟机 分别在两个虚拟机上开启3个Redis实例 3主3从两个虚拟机里的实例互为主备 下面分别在两个虚拟机上安装,网络设置参照codis集群的前两个主机 分别关闭 ...

  6. Redis 3.0集群 Window搭建方案

    Redis 3.0集群 Window搭建方案 1.集群安装前准备 安装Ruby环境,安装:rubyinstaller-2.3.0-x64.exe http://dl.bintray.com/onecl ...

  7. Redis+Tomcat+Nginx集群实现Session共享,Tomcat Session共享

    Redis+Tomcat+Nginx集群实现Session共享,Tomcat Session共享 ============================= 蕃薯耀 2017年11月27日 http: ...

  8. Redis进阶实践之十 Redis主从复制的集群模式

    一.引言        Redis的基本数据类型,高级特性,与Lua脚本的整合等相关知识点都学完了,说是学完了,只是完成了当前的学习计划,在以后的时间还需继续深入研究和学习.从今天开始来讲一下有关Re ...

  9. Redis进阶实践之十一 Redis的Cluster集群搭建

    一.引言      本文档只对Redis的Cluster集群做简单的介绍,并没有对分布式系统的详细概念做深入的探讨.本文只是提供了有关如何设置集群.测试和操作集群的说明,而不涉及Redis集群规范中涵 ...

  10. Redis进阶实践之十二 Redis的Cluster集群动态扩容

    一.引言     上一篇文章我们一步一步的教大家搭建了Redis的Cluster集群环境,形成了3个主节点和3个从节点的Cluster的环境.当然,大家可以使用 Cluster info 命令查看Cl ...

随机推荐

  1. L2-001. 紧急救援---(Dijkstra,记录路径)

    https://www.patest.cn/contests/gplt/L2-001 L2-001. 紧急救援 时间限制 200 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 ...

  2. swt MouseAdapter

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:     The method ...

  3. [Leetcode Week8]Subsets

    Subsets 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/subsets/description/ Description Given a set ...

  4. javascript写的轮播图

    欢迎指点! 先放上效果图: 鼠标移入界面后: <body onselectstart="return false;" style="-moz-user-select ...

  5. echarts 图表建立步骤

    需要引用的文件 <script src="web/mobile/js/jquery-1.8.3.min.js"></script> <script s ...

  6. javascript中a标签把href属性设置为“javascript:void(0)”还是会打开空白页面的问题

    在项目中有个位置的点击a标签这里要加一个权限判断,但是之前使用的是js动态添加a标签,href的属性值是一个url,但是我要做权限判断之后,我的url就不能设置在href属性中了,这样的话我可以在a标 ...

  7. Selenium2+python自动化43-判断title(title_is)【转载】

    前言 获取页面title的方法可以直接用driver.title获取到,然后也可以把获取到的结果用做断言. 本篇介绍另外一种方法去判断页面title是否与期望结果一种,用到上一篇Selenium2+p ...

  8. Python垃圾回收机制:gc模块(zz)

    在Python中,为了解决内存泄露问题,采用了对象引用计数,并基于引用计数实现自动垃圾回收. 由于Python 有了自动垃圾回收功能,就造成了不少初学者误认为不必再受内存泄漏的骚扰了.但如果仔细查看一 ...

  9. Go语言的切片slice基本操作

    感觉比数组好用,首选. package main import ( "fmt" ) //main is the entry of the program func main() { ...

  10. codeforces 739E

    官方题解是一个n2logn的dp做法 不过有一个简单易想的费用流做法 对每个小精灵,连边(A,i,1,pi) (B,i,1,ui) (i,t,1,0) (i,t,1,-pi*ui) 最后连边(s,A, ...