[置顶] redis3.2 学习记录 springmvc +jredis +redis 整合
2016-07-09 10:52
597 查看
首先linux安装redis
1、官网下载
2、tar -zxvf xxxxx.tar.gz
3、阅读readme文件,编译安装 进入目录 make , make test (可选) , make install
安装过程比较简单,安装过程可能会提示缺少相关的库,去网上找,然后安装就行了
redis 使用学习记录
============================
重启服务
pkill redis-server
然后再启动服务和客户端连接,注意:更改了redis的配置文件,启动时一定要加载redis.conf 否则更改的配置不生效
不加载配置文件启动方式:
/home/data/redis/src/redis-server
加载配置文件启动方式:
/home/data/redis/src/redis-server /home/data/redis/redis.conf &
或者
进到redis的安装目录下的src文件下,运行命令:
不加载配置文件启动方式:
./redis-server &
加载配置文件启动方式:
./redis-server /home/data/redis/redis.conf & (&符号代表交给后台运行)
打开redid自带的客户端
/home/data/redis/bin/redis-cli (打开redid自带的客户端)
或者
进到redis的安装目录下的src文件下,运行命令:
./redis-cli
有设置了认证密码的:使用 auth命令 进行授权认证
auth mypassword
直接使用密码打开redis 客户端:
./redis-cli -a mypassword
退出:exit
表明服务已启动。
$ redis-cli ping
PONG
本地 6379 端口号已被 redis 监听。
$ netstat -an | grep 6379
tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN
redis.conf配置文件:配置说明
1、requirepass mypassword
2、bind 绑定本机的ip
bind 192.168.1.102 (代表同一局域网都可以访问,注:192.168.1.102 是本机的局域网IP,并不是其他机器的IP)
bind 127.0.0.1 192.168.1.200(可以你绑定多个本机iP地址)
整合springmvc 简单例子
==================================
整合springmvc 简单例子
pom.xml
redis属性文件:
在spring的配置文件
redis模板基类:
user接口:
user接口实现:
user实体类
==========================
测试一 (本地测试redis)
测试二(基于spring 测试):
附上测试图一张:
1、官网下载
2、tar -zxvf xxxxx.tar.gz
3、阅读readme文件,编译安装 进入目录 make , make test (可选) , make install
安装过程比较简单,安装过程可能会提示缺少相关的库,去网上找,然后安装就行了
redis 使用学习记录
============================
重启服务
pkill redis-server
然后再启动服务和客户端连接,注意:更改了redis的配置文件,启动时一定要加载redis.conf 否则更改的配置不生效
不加载配置文件启动方式:
/home/data/redis/src/redis-server
加载配置文件启动方式:
/home/data/redis/src/redis-server /home/data/redis/redis.conf &
或者
进到redis的安装目录下的src文件下,运行命令:
不加载配置文件启动方式:
./redis-server &
加载配置文件启动方式:
./redis-server /home/data/redis/redis.conf & (&符号代表交给后台运行)
打开redid自带的客户端
/home/data/redis/bin/redis-cli (打开redid自带的客户端)
或者
进到redis的安装目录下的src文件下,运行命令:
./redis-cli
有设置了认证密码的:使用 auth命令 进行授权认证
auth mypassword
直接使用密码打开redis 客户端:
./redis-cli -a mypassword
退出:exit
表明服务已启动。
$ redis-cli ping
PONG
本地 6379 端口号已被 redis 监听。
$ netstat -an | grep 6379
tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN
redis.conf配置文件:配置说明
1、requirepass mypassword
2、bind 绑定本机的ip
bind 192.168.1.102 (代表同一局域网都可以访问,注:192.168.1.102 是本机的局域网IP,并不是其他机器的IP)
bind 127.0.0.1 192.168.1.200(可以你绑定多个本机iP地址)
整合springmvc 简单例子
==================================
整合springmvc 简单例子
pom.xml
<!-- spring-redis NoSql begin --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.0.2.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency> <!-- spring-redis NoSql end -->
redis属性文件:
# Redis settings redis.host=192.168.1.102 redis.port=6379 redis.pass=xuan123456 redis.maxIdle=300 redis.maxActive=600 redis.maxWait=1000 redis.testOnBorrow=true
在spring的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 读取项目的资源配置 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:hibernate.properties</value> <value>classpath:memcached.properties</value> <value>classpath:redis.properties</value> </list> </property> </bean> <!-- JDBC连接池 、数据源 --> <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="true" /> <property name="testOnReturn" value="false" /> <property name="validationQuery" value="SELECT 1" /> <property name="validationInterval" value="30000" /> <property name="timeBetweenEvictionRunsMillis" value="30000" /> <property name="maxActive" value="100" /> <property name="minIdle" value="2" /> <property name="maxWait" value="10000" /> <property name="initialSize" value="4" /> <property name="removeAbandonedTimeout" value="60" /> <property name="removeAbandoned" value="true" /> <property name="logAbandoned" value="true" /> <property name="minEvictableIdleTimeMillis" value="30000" /> <property name="jmxEnabled" value="true" /> </bean> <!-- MemcachedClient配置 --> <bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean"> <property name="servers" value="${memcached.servers}" /> <property name="protocol" value="${memcached.protocol}" /> <property name="transcoder"> <bean class="net.spy.memcached.transcoders.SerializingTranscoder"> <property name="compressionThreshold" value="1024" /> </bean> </property> <property name="opTimeout" value="${memcached.opTimeout}" /> <property name="timeoutExceptionThreshold" value="${memcached.timeoutExceptionThreshold}" /> <property name="locatorType" value="CONSISTENT" /> <property name="failureMode" value="Redistribute" /> <property name="useNagleAlgorithm" value="false" /> </bean> <!-- Redis Client配置 Begin --> <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> <!-- Redis Client配置 End --> </beans>
redis模板基类:
package com.springmvc.dao.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Repository; /** * * @author chenqixuan * * @param <K> * @param <V> */ @Repository public abstract class AbstractBaseRedisDao<K, V> { @Autowired protected RedisTemplate<K, V> redisTemplate; /** * 设置redisTemplate * @param redisTemplate the redisTemplate to set */ public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) { this.redisTemplate = redisTemplate; } /** * 获取 RedisSerializer * */ protected RedisSerializer<String> getRedisSerializer() { return redisTemplate.getStringSerializer(); } }
user接口:
package com.springmvc.dao; import java.util.List; import com.springmvc.domain.User; public interface IUserRedisDao { /** * 新增 *<br>------------------------------<br> * @param user * @return */ boolean add(User user); /** * 批量新增 使用pipeline方式 *<br>------------------------------<br> *@param list *@return */ boolean add(List<User> list); /** * 删除 * <br>------------------------------<br> * @param key */ void delete(String key); /** * 删除多个 * <br>------------------------------<br> * @param keys */ void delete(List<String> keys); /** * 修改 * <br>------------------------------<br> * @param user * @return */ boolean update(User user); /** * 通过key获取 * <br>------------------------------<br> * @param keyId * @return */ User get(String keyId); }
user接口实现:
package com.springmvc.dao.impl; import java.util.ArrayList; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import com.springmvc.dao.IUserRedisDao; import com.springmvc.domain.User; /** * * @author chenqixuan * */ @Repository public class UserRedisDao extends AbstractBaseRedisDao<String, String> implements IUserRedisDao{ /** * 新增 *<br>------------------------------<br> * @param user * @return */ public boolean add(final User user) { boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(user.getUserId()); byte[] name = serializer.serialize(user.getNickname()); return connection.setNX(key, name); } }); return result; } /** * 批量新增 使用pipeline方式 *<br>------------------------------<br> *@param list *@return */ public boolean add(final List<User> list) { Assert.notEmpty(list); boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); for (User user : list) { byte[] key = serializer.serialize(user.getUserId()); byte[] name = serializer.serialize(user.getNickname()); connection.setNX(key, name); } return true; } }, false, true); return result; } /** * 删除 * <br>------------------------------<br> * @param key */ public void delete(String key) { List<String> list = new ArrayList<String>(); list.add(key); delete(list); } /** * 删除多个 * <br>------------------------------<br> * @param keys */ public void delete(List<String> keys) { redisTemplate.delete(keys); } /** * 修改 * <br>------------------------------<br> * @param user * @return */ public boolean update(final User user) { String key = user.getUserId(); if (get(key) == null) { throw new NullPointerException("数据行不存在, key = " + key); } boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(user.getUserId()); byte[] name = serializer.serialize(user.getNickname()); connection.set(key, name); return true; } }); return result; } /** * 通过key获取 * <br>------------------------------<br> * @param keyId * @return */ public User get(final String keyId) { User result = redisTemplate.execute(new RedisCallback<User>() { public User doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(keyId); byte[] value = connection.get(key); if (value == null) { return null; } String name = serializer.deserialize(value); return new User(keyId, name, null, null, null, null, null); } }); return result; } }
user实体类
package com.springmvc.entity; // Generated 2016-4-24 22:42:31 by Hibernate Tools 3.2.2.GA import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * User generated by hbm2java */ @Entity @Table(name="user" ,catalog="springmvc_hibernate" ) public class User implements java.io.Serializable { /** * */ private static final long serialVersionUID = -8428363882220168049L; private String userId; private String nickname; private String email; private String tel; private String address; private Date addDate; private Integer age; public User() { } public User(String userId) { this.userId = userId; } public User(String userId, String nickname, String email, String tel, String address, Date addDate, Integer age) { this.userId = userId; this.nickname = nickname; this.email = email; this.tel = tel; this.address = address; this.addDate = addDate; this.age = age; } @Id @Column(name="user_id", unique=true, nullable=false, length=20) public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } @Column(name="nickname", length=20) public String getNickname() { return this.nickname; } public void setNickname(String nickname) { this.nickname = nickname; } @Column(name="email", length=20) public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } @Column(name="tel") public String getTel() { return this.tel; } public void setTel(String tel) { this.tel = tel; } @Column(name="address", length=65535) public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } @Temporal(TemporalType.TIMESTAMP) @Column(name="add_date", length=19) public Date getAddDate() { return this.addDate; } public void setAddDate(Date addDate) { this.addDate = addDate; } @Column(name="age") public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } }
==========================
测试一 (本地测试redis)
package com.redis.test; import org.apache.log4j.chainsaw.Main; import redis.clients.jedis.Jedis; public class JRedisDemo { public JRedisDemo() { // TODO Auto-generated constructor stub } public static void main(String args[]){ //程序入口 hellojedis(); } //测试redisJava客户端 jedis private static void hellojedis() { Jedis jedis = new Jedis("192.168.1.102",6379); jedis.auth("xuan123456");//redis 授权认证密码 //Jedis jedis= new Jedis("192.168.1.113",6379); //Jedis jedis= new Jedis("localhost",6379); jedis.set("chen", "HelloWorld!"); //String value = jedis.get("foo"); String str = jedis.get("chen"); //String val=jedis.get("uxuxuxux"); //System.out.println(value); System.out.println(str); System.out.println(jedis.get("xuan")); } }
测试二(基于spring 测试):
package com.redis.test; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import com.springmvc.dao.IUserRedisDao; import com.springmvc.entity.User; @ContextConfiguration(locations = { "classpath:spring-resource.xml","classpath:spring-hibernate.xml" }) public class RedisTest extends AbstractJUnit4SpringContextTests{ @Autowired private IUserRedisDao userRedisDao; /** * 新增 * <br>------------------------------<br> */ @Test public void testAddUser() { System.out.println("============redis test"); User user = new User(); user.setUserId("user12"); user.setNickname("java2000_wl"); boolean result = userRedisDao.add(user); //Assert.assertTrue(result); } /** * 批量新增 普通方式 * <br>------------------------------<br> */ @Test public void testAddUsers1() { List<User> list = new ArrayList<User>(); for (int i = 10; i < 50000; i++) { User user = new User(); user.setUserId("user" + i); user.setNickname("java2000_wl" + i); list.add(user); } long begin = System.currentTimeMillis(); for (User user : list) { userRedisDao.add(user); } System.out.println(System.currentTimeMillis() - begin); } /** * 批量新增 pipeline方式 * <br>------------------------------<br> */ @Test public void testAddUsers2() { List<User> list = new ArrayList<User>(); for (int i = 10; i < 1500000; i++) { User user = new User(); user.setUserId("user" + i); user.setNickname("java2000_wl" + i); list.add(user); } long begin = System.currentTimeMillis(); boolean result = userRedisDao.add(list); System.out.println(System.currentTimeMillis() - begin); Assert.assertTrue(result); } /** * 修改 * <br>------------------------------<br> */ @Test public void testUpdate() { User user = new User(); user.setUserId("user1"); user.setNickname("new_password"); boolean result = userRedisDao.update(user); Assert.assertTrue(result); } /** * 通过key删除单个 * <br>------------------------------<br> */ @Test public void testDelete() { String key = "user1"; userRedisDao.delete(key); } /** * 批量删除 * <br>------------------------------<br> */ @Test public void testDeletes() { List<String> list = new ArrayList<String>(); for (int i = 0; i < 10; i++) { list.add("user" + i); } userRedisDao.delete(list); } /** * 获取 * <br>------------------------------<br> */ @Test public void testGetUser() { String id = "user1"; User user = userRedisDao.get(id); Assert.assertNotNull(user); Assert.assertEquals(user.getNickname(), "java2000_wl"); } /** * 设置userRedisDao * @param userRedisDao the userRedisDao to set */ public void setuserRedisDao(IUserRedisDao userRedisDao) { this.userRedisDao = userRedisDao; } }
附上测试图一张:
相关文章推荐
- hiredis-vip库,集群,异步实例
- redis常用命令
- [置顶] php结合redis实现高并发下的抢购、秒杀功能
- redis配置文件详解
- zabbix监控redis单实例
- redis事物特性
- Redis - 排序
- Redis
- redis多实例运行
- 创建redis集群
- RedisTemplate的使用说明(常用接口方法)
- RedisTemplate的使用说明(序列化以及事物)
- Linux下php安装Redis扩展
- Redis数据库实现
- redis通用配置
- spring-data-redis操作redis集群
- Spring Redis基本使用
- Redis清除缓存方法
- Redis常用技巧
- 【Redis】——Redis简单介绍及Redis安装详细过程