redis3.2 學習記錄 springmvc +jredis +redis 整合
首先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
<!-- 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;
}
}
附上測試圖一張:
相關推薦
redis3.2 學習記錄 springmvc +jredis +redis 整合
首先linux安裝redis 1、官網下載 2、tar -zxvf xxxxx.tar.gz 3、閱讀readme檔案,編譯安裝 進入目錄 make , make test (可選) , make install 安裝過程比較簡單,安裝過程可能會提示缺少相關的庫,去網上
第011講:列表:一個打了激素的陣列2 | 學習記錄(小甲魚零基礎入門學習Python)
(標答出處: 魚C論壇) 《零基礎入門學習Python》 測試題: 1. 請問如何將下邊這個列表的’小甲魚’修改為’小魷魚’? list1 = [1, [1, 2, [‘小甲魚’]], 3, 5, 8, 13, 18] list1[1][2]='小魷魚' 2. 要對一個列表
第007、008講:了不起的分支迴圈1&2 | 學習記錄(小甲魚零基礎入門學習Python)
(標答出處: 魚C論壇) 《零基礎入門學習Python》 基礎題: if not (money < 100): 上邊這行程式碼相當於? if money >= 100: assert 的作用是什麼? assert斷言是宣告其布林值必須為真的判定,如果發
SpringMVC框架(1)之(1.2 入門程式—SpringMVC與Mybatis整合)
一、整合思路: 1. jar包: mybatis包、spring包、mybatis和spring整合包、資料庫驅動包、日誌包; 2. Spring管理: SpringMVC中編寫的 Handler(即Controller)、Mybatis的 SqlSessionFactory
OAuth 2 學習記錄
1. 基本概念 OAuth 2.0 授權框架可以讓第三方應用程式獲取Http服務有限的訪問許可權,傳統客戶端模型中,客戶端在請求訪問受限資源伺服器時,需要使用資源所有者(使用者)通過認證伺服器進行授權,但是這樣的方式是有一些缺陷的: 需要使用第三方應用程式來
第007、008講:了不起的分支迴圈1&2 | 學習記錄(小甲魚零基礎入門學習Python)
視訊中小甲魚使用 if elif else 在大多數情況下效率要比全部使用 if 要高,但根據一般的統計規律,一個班的成績一般服從正態分佈,也就是說平均成績一般集中在 70~80 分之間,因此根據統計規律,我們還可以改進下程式以提高效率。 題目備忘:按照100分制,90分以上成績為A,80到90為B,60到
SpringBoot學習記錄(三)——整合Mybatis
以前整合了Spring+SpringMVC+Mybatis,今天用SpringBoot整合了Mybatis,發現這個比之前的SSM的整合方便的太多,省去大量的配置檔案,也許是我還沒用到很深入吧,話不多說,直接進入正題。 1、建立一個SpringBoot專案: 2、下一步:
SpringBoot學習記錄(二)——整合JSP
雖然SpringBoot不推薦使用JSP,而是推薦使用Thymeleaf,但是以後說不定能用到,所以在學習的時候記錄一下 。直接上程式碼 在專案目錄下建一個webapp,然後在webapp下建一個jsp,如圖: pom.xml如下 <?xml version="
阿里雲部署redis3.2.100叢集注意事項redis cluster
由於安裝時忘記截圖,只有文字描述了 三臺雲伺服器 兩臺windows 一臺linux 6個redis服務 3主3從 在安全組要開放埠:如6379,伺服器中也要將埠暴露出來 叢集對外的總端 埠+10000,如16379也要開放出來 bind的設定 bind 0.0.0
Redis學習記錄(關於Redis的應用場景後期繼續補充)
之前對Redis並沒有什麼瞭解,然而今天看了一下快取相關的東西,需要用到Redis,就順便學了一下Redis。本文並不會記載很多關於Redis的使用方法,因為“菜鳥教程”中已經講得很清楚了。 Redis菜鳥教程:http://www.runoob.com/redis/redis-tutori
Centos7.2學習記錄(4)——調整root和home大小
df -h檢視磁碟使用情況 備份/home資料夾下內容 # cp -r /home/ homebak/ 解除安裝 /home # umount /home 如果失敗通過以下指令終止/ho
elasticsearch6.3.2學習記錄二 《spring boot 搭建es開發環境,建立索引,新增資料,查詢檢索》
spring boot + maven + idea jdk1.8以上 搭建 一、 pom.xml檔案 ,如果不需要連線資料庫,可以不引入資料庫連線依賴,在程式入口類加上這句註解 @EnableAutoConfiguration(exclud
dubbo2.5-spring4-mybastis3.2-springmvc4-mongodb3.4-redis3.2整合(六)Spring中Redis的快取的使用
前面已經寫了四篇關於dubbo2.5-spring4-mybastis3.2-springmvc4-mongodb3.4-redis3.2整合的文章: 快取(Caching)可以儲存經常會用到的資訊,這樣每次需要的時候,這些資訊都可以立即可用的。儘管Spr
【Redis】2、CentOS 7 上安裝 redis3.2.3安裝與配置
sync 倉庫 ace /var/ 發現 wan sudo base str 一、redis源碼安裝 【更正】現在最新穩定的版本已經到了3.2.8 截至到2016.8.11,redis最新穩定版本為3.2.3.本篇文章我們就以此版本為基礎,進行相關的講解。 下載redis源
Spring+SpringMVC+MyBatis深入學習及搭建(十四)——SpringMVC和MyBatis整合
文件拷貝 conf lips glib ide doc from ive body 轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/7010363.html 前面講到:Spring+SpringMVC+MyBatis深入學習及搭建(
Linux學習筆記4-CentOS7中redis3.2.9安裝教程
錯誤 img make .gz 需要 down images red pre redis下載地址:http://www.redis.cn/download.html 1、將下載過來的redis-3.2.9.tar.gz文件復制到/usr/local文件夾下 2、tar x
前端小白之每天學習記錄----php(2)數據庫操作軟件
blog 4行 pan 一個數 修改 列數 tor 清0 插入數據 數據庫 存儲數據的倉庫(軟件)(DBA:Database Administrator)數據庫管理員mysqlsqlserveroracle...... 數據庫軟件架構 C(client)->
Redis學習記錄
經歷 停止工作 切換 http 基本類 cache 數據保存 map 策略 參考資料: http://www.dengshenyu.com/%E5%90%8E%E7%AB%AF%E6%8A%80%E6%9C%AF/2016/01/09/redis-reactor-patte
mybatis學習(十一)——springmvc++spring+mybatis整合
transacti servlet 自動註入 為我 reac content attribute 定義 property 做任何一個項目都以一個需求,這裏先定義一下需求:利用三大框架查詢酒店列表。 一、搭建開發環境 1、創建一個web項目 我這裏用的是 jdk1.8+to
java一周學習記錄(2017/12/2)
統計 考試 lib 學習記錄 body width bsp 程序 table 姓名:Danny 日期:2017/12/2 任務 日期 聽課 編程程序 閱讀課本 準備考試 考試 周六加