zoukankan      html  css  js  c++  java
  • Spring集成Redis的两种方式Jedis和RedisTemplate

    Redis一种非关系型(K-V)数据库,也习惯称为Redis缓存,类似memcached,但相对与memcached又有着以下优点
    1 Redis不仅仅支持简单的k/v类型的数据,同时还提供list,set,hash等数据结构的存储。
    2 Redis支持数据的备份,即master-slave模式的数据备份。
    3 Redis支持数据的持久化,可以将内存中的数据保持在磁盘中,重启的时候可以再次加载进行使用。

    Spring框架基本上不用过多介绍,我相信点开本文的朋友基本上都很熟悉或者用过Spring框架了,在 java web开发方向,spring家族的地位应该一直处于最高的,本文要分享的是,通过Spring集成操作Redis数据库,大家会说这样的内容网上一大堆了,别着急,我们今天先分享两种方式,回头我们再进行对比一下。

    第一种方式:Jedis
    集成步骤:
    1. 添加jar包或者引入依赖
    
    
    <dependency>  
                <groupid>org.springframework.data</groupid>  
                <artifactid>spring-data-redis</artifactid>  
                <version>1.7.2.RELEASE</version>  
            </dependency>  
            <dependency>  
                <groupid>redis.clients</groupid>  
                <artifactid>jedis</artifactid>  
                <version>2.8.1</version>  
            </dependency> 
    2. 添加redis配置文件(非必须,可以在spring配置文件中直接配置)
    #访问地址 
    

    redis.host=127.0.0.1 

    #访问端口 

    redis.port=6379 

    #注意,如果没有password,此处不设置值,但这一项要保留 

    redis.password= 

    #最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。 

    redis.maxIdle=300 

    #连接池的最大数据库连接数。设为0表示无限制 

    redis.maxActive=600 

    #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。 

    redis.maxWait=1000 

    #在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的; 

    redis.testOnBorrow=true  



    3. 在applicationContext.xml添加redis的bean

      <!-- scanner redis properties  -->  
    
    
        <context:property-placeholder ignore-unresolvable="true" location="classpath:redis.properties">  
      
        <!--(1)如果你有多个数据源需要通过<context:property-placeholder管理,且不愿意放在一个配置文件里,那么一定要加上ignore-unresolvable=“true"-->  
        <!--(2)注意新版的(具体从哪个版本开始不清楚,有兴趣可以查一下)JedisPoolConfig的property name,不是maxActive而是maxTotal,而且没有maxWait属性,建议看一下Jedis源码。-->  
        <!-- redis连接池 -->  
        <bean class="redis.clients.jedis.JedisPoolConfig" id="jedisConfig">  
            <property name="maxTotal" value="${redis.maxActive}"></property>  
            <property name="maxIdle" value="${redis.maxIdle}"></property>  
            <property name="maxWaitMillis" value="${redis.maxWait}"></property>  
            <property name="testOnBorrow" value="${redis.testOnBorrow}"></property>  
        </bean>  
        <!-- redis连接工厂 -->  
        <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" id="connectionFactory">  
            <property name="hostName" value="${redis.host}"></property>  
            <property name="port" value="${redis.port}"></property>  
            <property name="password" value="${redis.password}"></property>  
            <property name="poolConfig" ref="jedisConfig"></property>  
        </bean>  
        <!-- redis操作模板,这里采用尽量面向对象的模板 -->  
        <bean class="org.springframework.data.redis.core.StringRedisTemplate" id="redisTemplate">  
            <property name="connectionFactory" ref="connectionFactory">  
            <!--     如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->  
            <property name="keySerializer">  
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer">  
            </bean></property>  
            <property name="valueSerializer">  
                <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer">  
            </bean></property>  
            <!--开启事务-->  
            <property name="enableTransactionSupport" value="true">  
        </property></property></bean>  
    </context:property-placeholder>
    4. 测试
       @Autowired
    

        private ShardedJedisPool shardedJedisPool;//注入ShardedJedisPool

        @RequestMapping(value = “/demo_set”,method = RequestMethod.GET)

        @ResponseBody

        public String demo_set(){

            //获取ShardedJedis对象

            ShardedJedis shardJedis = shardedJedisPool.getResource();

            //存入键值对

            shardJedis.set(“key1”,“hello jedis”);

            //回收ShardedJedis实例

            shardJedis.close();

            return “set”;

        }

        @RequestMapping(value = “/demo_get”,method = RequestMethod.GET)

        @ResponseBody

        public String demo_get(){

            ShardedJedis shardedJedis = shardedJedisPool.getResource();

            //根据键值获得数据

            String result = shardedJedis.get(“key1”);

            shardedJedis.close();

            return result;

        }



    第二种方式:

    1. 配置方式同Jedis,只是使用RedisTemplate进行数据操作
    2. 示例代码
        //配置类
    
    @Configuration
    
    @PropertySource("classpath:redis.properties")
    
    public class RedisConfig extends JCacheConfigurerSupport {
    
        @Autowired
    
        private Environment environment;
    
    
    
        @Bean
    
        public RedisConnectionFactory redisConnectionFactory() {
    
            JedisConnectionFactory fac = new JedisConnectionFactory();
    
            fac.setHostName(environment.getProperty("redis.hostName"));
    
            fac.setPort(Integer.parseInt(environment.getProperty("redis.port")));
    
            fac.setPassword(environment.getProperty("redis.password"));
    
            fac.setTimeout(Integer.parseInt(environment.getProperty("redis.timeout")));
    
            fac.getPoolConfig().setMaxIdle(Integer.parseInt(environment.getProperty("redis.maxIdle")));
    
            fac.getPoolConfig().setMaxTotal(Integer.parseInt(environment.getProperty("redis.maxTotal")));
    
            fac.getPoolConfig().setMaxWaitMillis(Integer.parseInt(environment.getProperty("redis.maxWaitMillis")));
    
            fac.getPoolConfig().setMinEvictableIdleTimeMillis(
    
                    Integer.parseInt(environment.getProperty("redis.minEvictableIdleTimeMillis")));
    
            fac.getPoolConfig()
    
                    .setNumTestsPerEvictionRun(Integer.parseInt(environment.getProperty("redis.numTestsPerEvictionRun")));
    
            fac.getPoolConfig().setTimeBetweenEvictionRunsMillis(
    
                    Integer.parseInt(environment.getProperty("redis.timeBetweenEvictionRunsMillis")));
    
            fac.getPoolConfig().setTestOnBorrow(Boolean.parseBoolean(environment.getProperty("redis.testOnBorrow")));
    
            fac.getPoolConfig().setTestWhileIdle(Boolean.parseBoolean(environment.getProperty("redis.testWhileIdle")));
    
            return fac;
    
        }
    
    
    
        @Bean
    
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    
            RedisTemplate<String, String> redis = new RedisTemplate<>();
    
            redis.setConnectionFactory(redisConnectionFactory);
    
            redis.afterPropertiesSet();
    
            return redis;
    
        }
    
    }
    
    //测试
    
    @RunWith(SpringJUnit4ClassRunner.class)
    
    @ContextConfiguration(classes = {RedisConfig.class})
    
    public class RedisTest {
    
    
    
        @Autowired
    
        private RedisTemplate<String, String> redisTemplate;
    
       
    
        @Test
    
        public void testRedisObj() {
    
            Map<String, Object> properties = new HashMap<>();
    
            properties.put("123", "hello");
    
            properties.put("abc", 456);
    
       
    
            redisTemplate.opsForHash().putAll("hash", properties);
    
       
    
            Map<Object, Object> ans = redisTemplate.opsForHash().entries("hash");
    
            System.out.println("ans: " + ans);
    
        }
    
    }
    
    

    //执行结果

    ans: {123=hello, abc=456}

     
     
  • 相关阅读:
    剧集更新表
    Pyhton资源
    JAVA资源
    012 循环
    011 条件判断
    010 使用list和tuple
    009 字符串和编码
    007 Python基础
    python 内置函数
    python 获取当前运行的类名函数名inspect.stack()[1][3]
  • 原文地址:https://www.cnblogs.com/javalinux/p/14360202.html
Copyright © 2011-2022 走看看