eclipse spring redis 整合-配置

花了一天时间折腾redis的配置

用到的jar

spring 3.1.1

aopalliance-1.0.jar

commons-pool2-2.3.jar

jedis-2.7.2.jar

spring-data-redis-1.6.6.RELEASE.jar

jedis和commons-pool2有版本依赖关系,所以要保证和上面一致

spring-data-redis版本 和 spring框架的版本也有依赖关系 所以要保证和上面一致

applicationContext-redis.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:aop="http://www.springframework.org/schema/aop"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <description>Redis configuration</description>

 <!-- 载入redis配置参数 -->
    <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>

     <!-- redis config start -->
   <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 

          <property name="maxIdle" value="${redis.pool.maxIdle}"></property>
          <property name="maxTotal" value="${redis.pool.maxActive}" />

          <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
          <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
          <!--
          <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property>
          <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property>
          <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property>-->
    </bean> 

     <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
      <property name="poolConfig" ref="jedisPoolConfig"></property>
      <property name="hostName" value="${redis.host}"></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.usePool}"></property> -->
 </bean> 

<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <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.StringRedisSerializer">
            </bean>
        </property>
    </bean>

    <!-- redis config end -->

</beans>

redis参数配置文件

#redis pool config
redis.pool.maxActive=200
redis.pool.maxIdle=100
redis.pool.maxWaitMillis=100
redis.pool.testOnBorrow=true

#redis config
redis.host=192.168.42.129
redis.port=6379
redis.timeout=2000
redis.password=qweasd
redis.dbindex=8
redis.usePool=1
redis.default.expire=1800000

测试代码

以下是网上的的教程==============================

  • 使用redis基本测试

maven导包

      <dependency>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
          <version>2.9.0</version>
      </dependency>

基本连接

public static void main(String[] args) {
        // 连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        // 查看服务是否运行
        System.out.println("服务正在运行: " + jedis.ping());
    }

存入string类型的值

public static void main(String[] args) {
        // 连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        //使用字符串string存值
        jedis.set("城市", "南京");
    }

在图形化redis客户端可以看到,存值成功

string类型取值

Jedis jedis = new Jedis("localhost");
        String city = jedis.get("城市");

存入list集合类型的值

public static void main(String[] args) {
        // 连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        //使用字符串list存值
        jedis.lpush("城市", "南京");
        jedis.lpush("城市", "上海");
        jedis.lpush("城市", "苏州");
        jedis.lpush("城市", "北京");
        jedis.lpush("城市", "南通");
    }

图形化界面展示效果

list集合取值

public static void main(String[] args) {
        // 连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        //list集合取值,这里注意的是,100的位置是结束的角标,如果大了没事,小了的话就会缺
        List<String> arr = jedis.lrange("城市", 0, 100);
        System.out.println(arr.size());
        for (String string : arr) {
            System.out.println(string);
        }
    }

存入Map的值

map类型存值又叫Redis hash ,是一个string类型的field和value的映射表

public static void main(String[] args) {
        //连接本地的jedis服务器
        Jedis jedis=new Jedis("localhost");

        //Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象。
        //这里要求的是map必须是key和value都是string类型的
        Map<String, String> map=new HashMap<>();
        map.put("name", "小明");
        map.put("age", "13");
        map.put("sex", "男");
        map.put("height", "174");

        //调用jedis的hmset(存入hash map)的方法将map的键值对存进去
        jedis.hmset("people", map);
    }

图形化客户端界面显示为:

map取值

public static void main(String[] args) {
        //连接本地的jedis服务器
        Jedis jedis=new Jedis("localhost");

        //新建一个string类型的数组,用于存当时存入redis的map的key值
        String[] arr=new String[4];
        arr[0]="name";
        arr[1]="age";
        arr[2]="sex";
        arr[3]="height";
        //利用jedis的hmget方法,从数据库中依次取出对应的map的key值
        List<String> list = jedis.hmget("people",arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println("存入键值对为:"+arr[i]+"--"+list.get(i));
        }

    }

结果为:

存入键值对为:name--小明
存入键值对为:age--13
存入键值对为:sex--男
存入键值对为:height--174

存入Set的值

Redis的Set是string类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。

存入代码:

public static void main(String[] args) {
        //连接本地的jedis服务器
        Jedis jedis=new Jedis("localhost");

        //使用list存入数据
        List<String> list=new ArrayList<>();
        list.add("北京");
        list.add("南京");
        list.add("上海");
        list.add("北京");
        list.add("北京");
        list.add("上海");
        list.add("苏州");
        list.add("南京");
        //打印源数据
        System.out.println("源数据为"+list);

        //因为jedis的sadd的方法,存入的是一个数组对象或者多数据,所有将集合对象转换成数组对象
        String[] arr=new String[list.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i]=list.get(i);
        }
        //调用sadd方法存入数据库
        jedis.sadd("city", arr);

    }

原来数据为:

源数据为[北京, 南京, 上海, 北京, 北京, 上海, 苏州, 南京]

redis数据库图形化客户端显示

可见,存入后,是把数据去重之后存储的.

set数据的取出

public static void main(String[] args) {
        //连接本地的jedis服务器
        Jedis jedis=new Jedis("localhost");

        //调用jedis的smembers方法,获取所有的set集合
        Set<String> smembers = jedis.smembers("city");

        System.out.println(smembers);
    }

控制台结果为:

[北京, 上海, 南京, 苏州]

存入sortset的值

Redis 有序集合和集合一样也是string类型元素的集合,且不允许重复的成员。

存入代码:

public static void main(String[] args) {
        //连接本地的jedis服务器
        Jedis jedis=new Jedis("localhost");

        Map<String, Double> map=new HashMap<>();
        map.put("北京", 1.0);
        map.put("北京", 2.0);
        map.put("南京", 3.0);
        map.put("上海", 4.0);
        map.put("上海", 5.0);
        map.put("南京", 6.0);

        //调用jedis的zadd方法存入
        jedis.zadd("city", map);
    }

图形化客户端界面:

南京在放入map时候,是在上海之前,可是最后score却取的是后面的一个.可见,如果有重复的数据产生的话,去重是将前面序号的重复去掉

取出代码:

public static void main(String[] args) {
        //连接本地的jedis服务器
        Jedis jedis=new Jedis("localhost");

        //索引在0,到10之间的,分数由高到底的取出所有的集合
        Set<String> zrevrange = jedis.zrevrange("city", 0, 10);
        System.out.println(zrevrange);

    }

控制台输出:

[南京, 上海, 北京]
  • 使用redis的基于spring测试

使用spring整合

applicationContext.xml中配置

名称空间:

xmlns:cache="http://www.springframework.org/schema/cache"
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache.xsd">

配置文件:

<!-- spring管理redis缓存管理器 -->
    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg index="0" ref="redisTemplate" />
    </bean>

    <cache:annotation-driven cache-manager="redisCacheManager" />

    <!-- jedis 连接池配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="300" />
        <property name="maxWaitMillis" value="3000" />
        <property name="testOnBorrow" value="true" />
    </bean>

    <!-- redis的连接工厂 -->
    <bean id="connectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="localhost" p:port="6379" p:pool-config-ref="poolConfig"
        p:database="0" />

    <!-- spring data 提供 redis模板  -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="keySerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                class="org.springframework.data.redis.serializer.StringRedisSerializer">
            </bean>
        </property>
    </bean>

在需要使用的service类中,使用注解

    //自动注入redis模板
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

使用spring整合string类型的值

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void Test01(){
        //通过模板,获取到String类型的redis对象
        ValueOperations<String, String> redisString = redisTemplate.opsForValue();

        //使用set方法,保存key和value的值
        redisString.set("city", "南京");

        //使用get(key)的方法获取到city对应的值
        String string = redisString.get("city");
        System.out.println(string);
    }

}

图形化界面:

控制台输出:

使用spring整合list类型的值

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void Test01(){

        //通过模板获取list类型的redis
        ListOperations<String, String> redisList = redisTemplate.opsForList();

        //通过key依次插入数据
        redisList.leftPush("city", "南京");
        redisList.leftPush("city", "上海");
        redisList.leftPush("city", "北京");
        redisList.leftPush("city", "上海");
        redisList.leftPush("city", "南京");

        //查找索引范围内的所有数据
        List<String> range = redisList.range("city", 0, 10);
        System.out.println(range);

    }

}

图形化客户端:

结果:

[南京, 上海, 北京, 上海, 南京]

使用spring整合Hash类型的值

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void Test01(){

        //通过模板对象,获取到redis的hash类型的对象
        HashOperations<String, Object, Object> redisMap = redisTemplate.opsForHash();

        //建立map集合
        Map<String, String> map=new HashMap<>();

        map.put("name", "小明");
        map.put("age", "18");
        map.put("length", "175");

        //存储hash对象
        redisMap.putAll("people", map);

        //获取数据库中存储的集合的key
        Set<Object> keys = redisMap.keys("people");
        //遍历key集合,获取到map中所有的value值
        for (Object key : keys) {
            Object value = redisMap.get("people", key);
            System.out.println(key+":"+value);
        }
    }
}

图形化客户端界面:

取值后的控制台界面:

name:小明
length:175
age:18

使用spring整合Set类型的值

代码示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void Test01(){
        //通过redis模板,创建set类型的redis对象
        SetOperations<String, String> redisSet = redisTemplate.opsForSet();

        //新建数组,赋值
        String[] arr=new String[5];
        arr[0]="南京";
        arr[1]="北京";
        arr[2]="南京";
        arr[3]="上海";
        arr[4]="北京";

        //调用set的add方法,存入key和数组
        redisSet.add("city", arr);

        //通过redis的获取成员方法,利用key获取到set集合
        Set<String> members = redisSet.members("city");
        System.out.println(members);

    }

}

图形化数据客户端界面:

控制台界面:

[北京, 南京, 上海]

由此可见,set类型的redis不是固定顺序的.

使用spring整合sortSet类型的值

由于set类型是不具有顺序的,而sortSet类型则具有顺序

代码示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void Test01(){

        //使用模板创建ZSet对象
        ZSetOperations<String, String> redisZSet = redisTemplate.opsForZSet();

        //存值,存value的同时,还加上顺序
        redisZSet.add("city", "南京", 1);
        redisZSet.add("city", "北京", 2);
        redisZSet.add("city", "上海", 3);
        redisZSet.add("city", "南京", 4);
        redisZSet.add("city", "上海", 5);
        redisZSet.add("city", "南京", 6);

        //获取范围顺序里面的值
        Set<String> rangeByScore = redisZSet.rangeByScore("city", 1, 10);
        System.out.println(rangeByScore);

    }

}

图形化客户端界面:

控制台数据:

原文地址:https://www.cnblogs.com/cfas/p/9351597.html

时间: 2024-08-02 10:27:11

eclipse spring redis 整合-配置的相关文章

Spring+Hibernate整合配置 --- 比较完整的spring、hibernate 配置

Spring+Hibernate整合配置 分类: J2EE2010-11-25 17:21 16667人阅读 评论(1) 收藏 举报 springhibernateclassactionservletmysql 在公司一直没有什么机会直接折腾SSH“原生态”的SSH当今比较流行的轻量级的框架,用着公司的框架也是郁闷异常,今天没事整整原来用过的一个项目的配置,发现就算是自己曾经用过的东西,如果较长时间不返过去重新学习,许多你半熟不熟的知识就是异常陌生.下面贴上我的一些配置,暂且权当备份吧. web

Spring Hibernate4 整合配置文档

1 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:context="http:/

spring redis整合

1,利用spring-data-redis整合 项目使用的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/ma

spring redis 整合

<import resource="cache/applicationContext-redis.xml"/> applicationContext-redis.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation

maven项目下solr和spring的整合配置

前言: solr和spring整合其实很简单,只要注意导入依赖的配置文件即可.废话不多说,上代码. 第一步:编写maven项目的pom文件,导入依赖 [html] view plain copy<project?xmlns="http://maven.apache.org/POM/4.0.0"?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"??????xsi:schemaLocation="

在spring,mybatis整合配置中走的弯路(1)

在接触一个新东西,总免不了走一些弯路,也正是在这些弯路中,我们不断的成长. 从git上把之前写的代码扒下来,看看我在当初使用spring与mybatis中所走的弯路,路过的君子也可引以为戒. <!-- 事务管理器 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name

Spring Redis Session配置

        <context:property-placeholder location="classpath:config.properties"/> <!-- 单个redis配置 --> <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>   <b

SpringMVC+Spring+Mybatis整合配置

1.Maven依赖文件: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/maven-v4_0_0.xsd"&g

Spring+redis整合遇到的问题集以及注意事项

redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorted set --有序集合)和hash(哈希类型).这些数据类型都支持push/pop.add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的.在此基础上,redis支持各种不同方式的排序.与memcached一样,为了保证效率,数据都是缓存在内存中.区别的是redis会周期性的把更新的数