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

后续在此基础上继续深入学习。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值