1. 程式人生 > >spring+redis搭建(測試學習之一)

spring+redis搭建(測試學習之一)

本人剛接觸redis,特記錄學習過程,後續持續深入。

環境說明:
1、MyEclipse 2015 CI+jdk1.8.0_121+redis3.2.8+maven3.2.1

搭建最簡單的spring+redis如下:

2pom.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>redis</groupId> <artifactId>redis</artifactId> <version>0.0.1-SNAPSHOT</version> <build> </build> <dependencies> <dependency> <groupId>
org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.0.2.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId
>
servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> </project>

3、配置spring:applicationContext.xml

<?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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">


<!--註解說明 -->
<context:annotation-config />

<!-- 把標記了@Controller註解的類轉換為bean -->
<context:component-scan base-package="com.mkfree.**" />

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

    <!-- p:password="${redis.pass}" -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="${redis.host}" p:port="${redis.port}"   p:pool-config-ref="poolConfig"/>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory"  ref="connectionFactory" />
    </bean>     
    <!-- redis服務封裝 -->
<bean id="redisService" class="com.mkfree.redis.test.RedisService">
</bean>
</beans>

4、配置redis資料庫連線:

# Redis settings
redis.host=192.168.8.118#這裡為redis安裝的伺服器IP地址
redis.port=6379#redis埠號
#redis.pass=java2000_wl


redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true

5、RedisService為實現控制類,裡面包含了一些增刪改的操作,大家調通自己完善。

package com.mkfree.redis.test;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import redis.clients.jedis.Jedis;

/**
 * 封裝redis 快取伺服器服務介面
 * @author doop
 *@version 1.0 測試版,聯絡使用
 */
public class RedisService {

    /**
     * 通過key刪除(位元組)
     * @param key
     */
    public void del(byte [] key){
        this.getJedis().del(key);
    }
    /**
     * 通過key刪除
     * @param key
     */
    public void del(String key){
        this.getJedis().del(key);
    }

    /**
     * 新增key value 並且設定存活時間(byte)
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(byte [] key,byte [] value,int liveTime){
        this.set(key, value);
        this.getJedis().expire(key, liveTime);
    }
    /**
     * 新增key value 並且設定存活時間
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(String key,String value,int liveTime){
        this.set(key, value);
        this.getJedis().expire(key, liveTime);
    }
    /**
     * 新增key value
     * @param key
     * @param value
     */
    public void set(String key,String value){
        this.getJedis().set(key, value);
    }
    /**新增key value (位元組)(序列化)
     * @param key
     * @param value
     */
    public void set(byte [] key,byte [] value){
        this.getJedis().set(key, value);
    }
    /**
     * 獲取redis value (String)
     * @param key
     * @return
     */
    public String get(String key){
        String value = this.getJedis().get(key);
        return value;
    }
    /**
     * 獲取redis value (byte [] )(反序列化)
     * @param key
     * @return
     */
    public byte[] get(byte [] key){
        return this.getJedis().get(key);
    }

    /**
     * 通過正則匹配keys
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern){
        return this.getJedis().keys(pattern);
    }

    /**
     * 檢查key是否已經存在
     * @param key
     * @return
     */
    public boolean exists(String key){
        return this.getJedis().exists(key);
    }
    /**
     * 清空redis 所有資料
     * @return
     */
    public String flushDB(){
        return this.getJedis().flushDB();
    }
    /**
     * 檢視redis裡有多少資料
     */
    public long dbSize(){
        return this.getJedis().dbSize();
    }
    /**
     * 檢查是否連線成功
     * @return
     */
    public String ping(){
        return this.getJedis().ping();
    }
    /**
     * 獲取一個jedis 客戶端
     * @return
     */
    private Jedis getJedis(){
        if(jedis == null){
            return jedisConnectionFactory.getShardInfo().createResource();
        }
        return jedis;
    }
    private RedisService (){

    }
    //操作redis客戶端
    private static Jedis jedis;
    @Autowired
    @Qualifier("connectionFactory")
    private JedisConnectionFactory jedisConnectionFactory;
}

6、測試類

package com.mkfree.redis.test;

import java.util.Set;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * redis spring 簡單例子
 * @author doop
 *
 */
public class TestRedis {

    public static void main(String[] args) throws InterruptedException {
        ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //這裡已經配置好,屬於一個redis的服務介面
        RedisService redisService = (RedisService) app.getBean("redisService");

        String ping = redisService.ping();//測試是否連線成功,連線成功輸出PONG
        System.out.println(ping);

        //首先,我們看下redis服務裡是否有資料
        long dbSizeStart = redisService.dbSize();
        System.out.println(dbSizeStart);

        redisService.set("username", "oyhk");//設值(查看了原始碼,預設存活時間30分鐘)
        String username = redisService.get("username");//取值 
        System.out.println(username);
        redisService.set("username1", "oyhk1", 1);//設值,並且設定資料的存活時間(這裡以秒為單位)
        String username1 = redisService.get("username1");
        System.out.println(username1);
        Thread.sleep(2000);//我睡眠一會,再去取,這個時間超過了,他的存活時間
        String liveUsername1 = redisService.get("username1");
        System.out.println(liveUsername1);//輸出null

        //是否存在
        boolean exist = redisService.exists("username");
        System.out.println(exist);

        //檢視keys
        Set<String> keys = redisService.keys("*");//這裡檢視所有的keys
        System.out.println(keys);//只有username username1(已經清空了)

        //刪除
        redisService.set("username2", "oyhk2");
        String username2 = redisService.get("username2");
        System.out.println(username2);
        redisService.del("username2");
        String username2_2 = redisService.get("username2");
        System.out.println(username2_2);//如果為null,那麼就是刪除資料了

        //dbsize
        long dbSizeEnd = redisService.dbSize();
        System.out.println(dbSizeEnd);

        //清空reids所有資料
        //redisService.flushDB();
    }
}

接下來就可以除錯了,如果報錯為DENIED Redis is running in protected mode because protected mode is enabled,說明:
redis 報錯 Redis protected-mode 配置檔案沒有真正啟動,具體處理方式如下:

(error) DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the lookback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the --portected-mode no option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

則按照如下來設定:

(error) DENIED Redis is running in protected mode because protected mode is enabled
Redis protected-mode 是3.2 之後加入的新特性,在Redis.conf的註釋中,我們可以瞭解到,他的具體作用和啟用條件
連結redis 時只能通過本地localhost (127.0.0.1)這個來連結,而不能用網路ip(192.168..)這個連結,問題然如果用網路ip 連結會報以下的錯誤:

(error) DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the lookback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the --portected-mode no option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.
是說處於保護模式,只能本地連結,我們需要修改配置檔案../redis.conf 
1)開啟配置檔案把下面對應的註釋掉

# bind 127.0.0.1 
2)Redis預設不是以守護程序的方式執行,可以通過該配置項修改,使用yes啟用守護程序,設定為no

daemonize no
3)保護模式

protected-mode no 
4)最後關鍵的是: 
沒反應應該是你啟動服務端的時候沒有帶上配置檔案。你可以./redis-server redis.conf 
你配置好了,但要重新啟動redis,如果還是報一樣的錯誤,很可能是沒有啟動到配置檔案,所以需要真正的和配置檔案啟動需要: 
在redis.conf檔案的當前目錄下:

$ redis-server redis.conf
如果還是所某個埠已在使用,那麼可能是有 後臺程式在佔用該埠,需要kill 掉該程式,重新帶上配置檔案。./redis-server redis.conf啟動。 
將含有”redis”關鍵詞的程序殺死:

$ ps -ef | grep redis | awk ‘{print $2}’ | xargs kill -9
我的問題就是這個步驟解決的

7、最後執行成功:

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
PONG
3
oyhk
oyhk1
null
true
[myhash, name, username]
oyhk2
null
3

後續在此基礎上繼續深入學習。

相關推薦

spring+redis搭建測試學習之一

本人剛接觸redis,特記錄學習過程,後續持續深入。 環境說明: 1、MyEclipse 2015 CI+jdk1.8.0_121+redis3.2.8+maven3.2.1 搭建最簡單的spring+redis如下: 2pom.xml配置如下;

spring的Java配置入門Spring Boot學習之一

配置文件 png bean 日誌 簡單 pom artifact 簡單的 ret spring的Java配置 1、創建maven項目 使用idea創建maven項目,這裏順便提一下,idea真的比eclipse好用,早點熟悉吧。然後就是maven是java項目管理最主流的工

學習 Spring Boot:二十九Spring Boot Junit 單元測試

前言 JUnit 是一個迴歸測試框架,被開發者用於實施對應用程式的單元測試,加快程式編制速度,同時提高編碼的質量。 JUnit 測試框架具有以下重要特性: 測試工具 測試套件 測試執行器 測試分類 瞭解 Junit 基礎方法 加入依賴 在 p

Ubuntu 16.04下Redis Cluster集群搭建官方原始方案

選擇 正數 mil 請求 點數據 包含 最終 util 交互 前提:先安裝好Redis,參考:http://www.cnblogs.com/EasonJim/p/7599941.html 說明:Redis Cluster集群模式可以做到動態增加節點和下線節點,使用起來非常

Spring Boot教程三十四使用Redis數據庫2

分享圖片 target object docs int cpp eas 序列 lean 除了String類型,實戰中我們還經常會在Redis中存儲對象,這時候我們就會想是否可以使用類似RedisTemplate<String, User>來初始化並進行操作。但是

手機自動化測試環境搭建eclipse+python+uiautomator

list fig finish java環境 pda 所有 開發 界面 自己 最近在公司做了一個階段的手機APP自動化測試,是在已有的環境基礎上進行腳本開發,所有對基礎的環境搭建不是很清楚,後來自己閑來無事就在家裏搭建了一下下,接下來和大家分享一下搭建過程。 一:搭建手機A

Java項目框架搭建系列Java學習路線

Java 編程語言 前言:已經工作4年,真是時間飛逝。其實當你在一間公司工作一兩年之後,公司用到的開發框架的基本使用你應該都會了。你會根據一個現有項目A復制一下搭建出另外一個類似框架的項目B,然後在項目B上進行業務邏輯開發。如果你更努力一點,你可能有去摸索一些配置的作用,一些問題的排查會更有經驗和自己

Redis搭建:主從復制

運維 edi 地址 操作 pass 配置文件 發送 提高 快照 一、引言 Redis有三種集群模式: 第一個就是主從模式 第二種“哨兵”模式,在Redis 2.6版本開始提供,2.8版本穩定 第三種是Cluster集群模式,在Redis 3.x以後的版本才增加進來的 二

Redis搭建:單實例

.tar.gz div clas moni 設定 prefix spa usr info 環境:CentOS6.4 + redis3.2.4 一、安裝 cd /opt tar -zxf redis-3.2.4.tar.gz make make install PREFIX

Redis搭建:Sharding集群模式

serve nsis bsp 快照 一致性 打開 copy 列表 sentinal 一、 方案 1. 介紹redis集群分為服務端集群(Cluster)和客戶端分片(Sharding)服務端集群:redis3.0以上版本實現,使用哈希槽,計算key的CRC16結果再模168

spring-springmvc搭建springMVC添加對靜態資源訪問的支持及對Fastjson的支持

gmv port ack register repos servle 配置 als img 1.添加對靜態資源.js/.img/.css的訪問 方式有3種: 1,更改springmvc 的DispatherServlet的urlpattern的路徑改為“/*

201771010126 王燕《面向物件程式設計Java》第十四周學習總結測試程式11

實驗十四  Swing圖形介面元件 理論部分: 不使用佈局管理器 有時候可能不想使用任何佈局管理器,而只 是想把元件放在一個固定的位置上。下面是將一 個元件定位到某個絕對定位的步驟: 1)將佈局管理器設定為null。 2)將元件新增到容器中。 3)指定想要放置的位置和大小。 f

JavaEE MyBatis與Spring的整合——基於mapper介面方式開發教材學習筆記

在MyBatis與Spring的整合開發中雖然可以通過傳統的DAO開發方式,但是採用DAO方式會產生大量的重複程式碼,因此學習另外一種程式設計方式就很重要了,即Mapper介面程式設計(本章程式碼是基於上一篇部落格的點這裡) 一、基於MapperFactoryBean的整合 Mapper

JavaEE Spring與MyBatis的整合之傳統DAO方式整合教材學習筆記

在實際開發中MyBatis都是與Spring整合在一起使用的,在之前學習了MyBatis與Spring,現在來學習如何使他們整合 首先建立一個名為chapter10的web專案 一、環境搭建 1.準備好所有的有關jar包,具體如下: 將上面所有jar包新增到專案lib目錄下

JavaEE MyBatis關聯對映之一對多教材學習筆記

在實際應用中,應用更多的是一對多,例如每一個使用者可以有多個訂單,在使用MyBatis中是怎樣處理一對多的關係呢,在MyBatis對映檔案中有一個resultMap元素,此元素包含一個<collection>子元素,MyBatis就是通過他來處理一對多關係的, 下面通過一個案例瞭

JavaEE Spring MVC入門——第一個Spring MVC應用程式教材學習筆記

Spring MVC 是Spring提供的一個實現了Web MVC設計模式的輕量級Web框架, 下面通過一個小例子學習一下什麼是Spring MVC 一、建立專案,引入jar包 在Eclipse中建立一個名為chapter11的web專案,在專案的lib目錄下匯入所需的jar包,具體

搭建Django環境實驗樓學習筆記

安裝 首先,我們要下載Django,編寫此課程時Django新版為2.0.6,為避免出現不必要的麻煩,請大家在實驗時也使用此版本。 開啟終端,輸入以下命令: $ sudo pip3 install Django==2.0.6 測試Django安裝 我們可以在終端中測試Djang

Windows 下 Redis叢集的搭建 ——超詳細版

1、下載並安裝Redis 本人安裝到C盤了,在C:\Redis 下建立Logs資料夾 , 然後在C:\Redis 建立 3個不同的Redis例項    ①、 redis.6380.co

文字情感分類---搭建LSTM深度學習模型做文字情感分類的程式碼

來源:http://mp.weixin.qq.com/s?__biz=MzA3MDg0MjgxNQ==&mid=2652391534&idx=1&sn=901d5e55971349697e023f196037675d&chksm=84da48

三大框架之Spring 初級學習 2

1. AOP * AOP:Aspect Oriented Programming,面向切面程式設計 * * 在日誌和異常處理方面很常用 * *