Redis入门实例(Redis+Sprint+maven创建工程)

一.>创建一个maven工程应用和相关配置:Redis_study,创建工程应用过程略

1.>配置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>Redis_dom1</groupId>
  <artifactId>Redis_study</artifactId>
  <version>01</version>
  <packaging>war</packaging>
  <name>Redis_study xzh</name>
  
      <build>  
        <!-- ###########给出构建过程中所用到的插件start######## --> 
        <plugins>
            <!-- 由于maven默认使用的jdk与工程配置的jdk版本不一致,导致无法编译通过,通过该插件指定jdk版本 -->  
            <plugin>  
                <groupId>org.apache.maven.plugins</groupId>  
                <artifactId>maven-compiler-plugin</artifactId>  
                <configuration>  
                    <source>1.7</source>  
                    <target>1.7</target>  
                    <encoding>UTF-8</encoding>  
                </configuration>  
            </plugin>
            <!-- maven-surefire-plugin 是maven里执行测试用例的插件,不显示配置就会用默认配置。这个插件的 surefire:test 命令会默认绑定maven执行的 test 阶段 -->  
            <plugin>  
                <groupId>org.apache.maven.plugins</groupId>  
                <artifactId>maven-surefire-plugin</artifactId>  
                <configuration>  
                    <!-- 跳过测试单元 true:跳过测试,false不跳过(默认)-->  
                    <skip>true</skip>  
                </configuration>  
            </plugin>  
        </plugins> 
        <!-- ###########给出构建过程中所用到的插件end######## --> 
    </build>  
    
    <properties>
        <spring.version>3.2.3.RELEASE</spring.version>
    </properties>
    
    <dependencies>
        <!-- junit依赖 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- Redis客户端jedis依赖 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!-- spring-data-redis依赖 -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.5.0.RELEASE</version>
        </dependency>

        <!-- spring相关 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</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-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
</project>

2.>配置Redis属性文件redis.properties:文件内容如下

 

#redis.hostName=localhost
#配置服务器ip地址
redis.hostName=***.***.***.** redis.port=6379 redis.password=redisroot redis.timeout=5000 redis.pool.maxActive=200 redis.pool.maxIdle=50 redis.pool.minIdle=20 redis.pool.maxWait=3000 redis.pool.testOnBorrow=true redis.pool.testOnReturn=true redis.pool.usePool=true

 

3.>配置Spring启动需初始化的上下文bean:application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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-4.0.xsd  
       http://www.springframework.org/schema/context  
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--使用注解 -->
    <context:annotation-config />

    <!-- 加载redis配置文件 -->
    <context:property-placeholder location="classpath:redis.properties" />
    <bean id="jedisPoolConfig1" class="redis.clients.jedis.JedisPoolConfig">
    </bean> 
    
    <!-- ################RedisTemplate操作模板配置begin##################### -->
    <bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
        <property name="hostName" value="${redis.hostName}"></property>
           <property name="port" value="${redis.port}"></property>
           <property name="password" value="${redis.password}"></property>
           <property name="timeout" value="${redis.timeout}"></property>
           <property name="usePool" value="${redis.pool.usePool}"></property>
        <property name="poolConfig" ref="jedisPoolConfig1"></property>
    </bean>

    <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
        <property name="keySerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
    </bean>
    <!-- ################RedisTemplate操作模板配置end##################### -->
    
    <!-- ################JedisPool操作配置begin ##############################-->
    <!-- Redis连接池的配置 -->
    <bean id="jedisPoolConfig2" class="redis.clients.jedis.JedisPoolConfig" >
        <property name="maxTotal" value="${redis.pool.maxActive}"/> <!-- 控制一个pool可分配多少个jedis实例 --> 
        <property name="maxIdle" value="${redis.pool.maxIdle}"/> <!-- 控制一个pool最多有多少个状态为idle(空闲)的jedis实例 -->
        <property name="minIdle" value="${redis.pool.minIdle}"/> <!-- 控制一个pool最少有多少个状态为idle(空闲)的jedis实例 -->
        <property name="maxWaitMillis" value="${redis.pool.maxWait}"/><!-- 表示当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException -->
        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/><!-- 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的 --> 
        <property name="testOnReturn" value="${redis.pool.testOnReturn}"/>
    </bean>
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig2"/>
        <constructor-arg index="1" value="${redis.hostName}" />
        <constructor-arg index="2" value="${redis.port}" />
        <constructor-arg index="3" value="${redis.timeout}" />
        <!--Redis密码-->
        <constructor-arg index="4" value="${redis.password}" />
    </bean>
    <!-- ################JedisPool操作配置end ################################-->
    
</beans>  

二.>编写测试代码

1.>编写Spring单位测试加载基础类:BaseTest.java

package redis;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.ContextConfiguration;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//指定bean注入的配置文件
@ContextConfiguration(locations = {"classpath:application.xml"})
//使用标准的JUnit @RunWith 注释运行Spring Test Runner
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseTest extends AbstractJUnit4SpringContextTests {}

2.>编写测试类:RedisTest.java

 

package redis;
import java.util.concurrent.TimeUnit;
import java.util.Map;
import java.util.HashMap;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
 * 
 * @ClassName: RedisTest 
 * @Description: TODO
 * @author xzh
 * @date 20170323 
 *
 */
public class RedisTest extends BaseTest 
{
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private JedisPool jedisPool;
    public Map<String,String> student = new HashMap<String,String>();
    /**
     * 测试插入与获取Redis的数据
     * @Title: testPutAndGet 
     * @Description: TODO
     * @throws
     */
    @Test
    public void testPutAndGet() 
    {
        System.out.println(this.getClass().getName()+"testPutAndGet");
        redisTemplate.opsForHash().put("user", "name", "rhwayfun");
        Object object = redisTemplate.opsForHash().get("user", "name");
        System.out.println(object);
    }
    /**
     * 测试Redis作为缓存的例子
     * @Title: testCache 
     * @Description: TODO
     * @throws InterruptedException
     * @throws
     */
    @Test
    public void testCache() throws InterruptedException 
    {
        //-------jedisPool配置使用--redisTemplate--进行操作Start-------------//
        System.out.println("-------jedisPool配置使用--redisTemplate--进行操作Start-------------");
        // 插入一条数据
        redisTemplate.opsForHash().put("user", "name", "rhwayfun");
        // 设置失效时间为6秒
        redisTemplate.expire("user", 6, TimeUnit.SECONDS);
        // 3秒后获取
        Thread.sleep(3000);
        Object object = redisTemplate.opsForHash().get("user", "name");
        System.out.println("3秒后:" + object);
        // 7秒后获取
        Thread.sleep(4000);
        object = redisTemplate.opsForHash().get("user", "name");
        System.out.println("7秒后:" + object);
        System.out.println("-------jedisPool配置使用--redisTemplate--进行操作end---------------\n");
        //-------jedisPool配置使用--redisTemplate--进行操作end-------------//
        
        //-------jedisPool配置使用----Jedis----进行操作Start-------------//
        System.out.println("-------jedisPool配置使用Jedis的进行操作Start-------------");
        Jedis jedis = jedisPool.getResource();
        System.out.println("服务器IP地址:"+jedis.configGet("bind"));
        /*hash api:hset*/
        jedis.hset("me", "name", "xzh");
        System.out.println("jedis.hset(me, name, xzh):" + jedis.hget("me", "name"));
        
        /*hash api:hmset*/
        student.put("naem","xzh");
        student.put("stid", "1");
        jedis.hmset("student", student);
        
        //关闭连接
        if(jedis != null)
        {
            student.clear();
            jedisPool.close();
        }
        System.out.println("-------jedisPool配置使用Jedis的进行操作end--------------\n");
        //-------jedisPool配置使用----Jedis----进行操作end-------------//
    }
}

运行结果:运行之前先搭建号redis缓存服务,右键点击方法名,选择则“Run As”→“JUnit Test”即可

......
-------jedisPool配置使用--redisTemplate--进行操作Start-------------
3秒后:rhwayfun
7秒后:null
-------jedisPool配置使用--redisTemplate--进行操作end---------------

-------jedisPool配置使用Jedis的进行操作Start-------------
服务器IP地址:[bind, 127.0.0.1 192.168.248.85]
jedis.hset(me, name, xzh):xzh
-------jedisPool配置使用Jedis的进行操作end--------------

redis.RedisTesttestPutAndGet
rhwayfun

 

右键点击方法名,选择则“Run As”→“JUnit Test”即可

转载于:https://www.cnblogs.com/zhabayi/p/6605717.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Redis实例和Keepalived是一种常见的高可用性解决方案,用于确保Redis服务的持续可用性。在这种架构中,多个Redis实例运行在不同的主机上,并使用Keepalived来监控和管理这些实例。 首先,让我们了解一下Redis实例的工作原理。每个Redis实例都有自己的配置文件和端口号,它们可以在同一台主机上或不同的主机上运行。每个实例都有自己的数据集,并独立地处理客户端请求。 要实现高可用性,我们可以使用Keepalived来监控这些Redis实例,并在主实例发生故障时自动切换到备用实例。Keepalived是一个基于VRRP(Virtual Router Redundancy Protocol,虚拟路由冗余协议)的工具,它可以确保多个主机之间的故障转移。 下面是一种使用Redis实例和Keepalived的架构示例: 1. 配置多个Redis实例:在每个主机上安装和配置多个Redis实例,确保它们使用不同的端口号和配置文件。每个实例可以通过不同的配置文件指定不同的端口号、数据目录和日志文件等。 2. 安装并配置Keepalived:在每个主机上安装Keepalived,并配置一个共享虚拟IP(VIP)。Keepalived会监控Redis实例的运行状态,并在主实例发生故障时将VIP切换到备用实例。 3. 配置Keepalived的监控和故障切换:在Keepalived配置文件中,指定要监控的Redis实例和故障切换的条件。例如,可以设置当主实例无法正常响应时,将VIP切换到备用实例。 4. 测试高可用性:启动Redis实例和Keepalived,并进行故障测试。模拟主实例故障时,观察Keepalived是否能够正确地将VIP切换到备用实例,并确保客户端可以继续访问Redis服务。 需要注意的是,Redis实例和Keepalived只能提供故障转移和高可用性保证,并不能解决数据同步和负载均衡的问题。如果需要在多个Redis实例之间进行数据同步或负载均衡,可以考虑使用Redis Sentinel或Redis Cluster等其他解决方案。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值