Redis spring 使用总结

原创
2016/09/07 14:38
阅读数 204

1.1 Redis介绍

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

Redis数据库完全在内存中,使用磁盘仅用于持久性。相比许多键值数据存储,Redis拥有一套较为丰富的数据类型。Redis可以将数据复制到任意数量的从服务器。

1.2 Redis优点

 (1)异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。

(2)支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。

(3)操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。

(4)多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页命中计数等。

1.3 Redis缺点

 (1)单线程

(2)耗内存

2.1 redis启动

 已经开启了对应服务的,我们让它保持,下面例子需要用到。如果没有开启的,我们命令开启,进入Redis的安装目录(博主的是C:\Program Files\Redis),然后如下命令开启:

redis-server  redis.windows.conf

如果启动报错,请检查以下配置,

3.1 maven pom配置

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.6.0.RELEASE</version>
</dependency>

<!--redis client config-->
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.1</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>${jedis.version}</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>

3.2 spring配置

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxTotal" value="${redis.pool.maxTotal}"/>
    <property name="maxIdle"  value="${redis.pool.maxIdle}" />
    <property name="testOnBorrow"  value="${redis.pool.testOnBorrow}" />
</bean>

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="${redis.ip}" />
    <property name="port" value="${redis.port}" />
    <property name="usePool" value="true" />
    <property name="poolConfig" ref="jedisPoolConfig" />
    <property name="timeout" value="${redis.timeout}"/>
</bean>
<!-- redisTemplate模板 -->
<bean id="stringRedisSerializer"
      class="org.springframework.data.redis.serializer.StringRedisSerializer" />
<bean id="kryoRedisSerializer" class="com.supuy.core.util.KryoRedisSerializer"/>
<bean id="jdkRedisSerializer"
      class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="jedisConnectionFactory"/>
    <property name="KeySerializer" ref="stringRedisSerializer" />
    <property name="ValueSerializer" ref="stringRedisSerializer" />
    <property name="hashKeySerializer" ref="stringRedisSerializer"/>
    <property name="hashValueSerializer" ref="jdkRedisSerializer"/>
</bean>
<bean id="redisTransaction" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="jedisConnectionFactory"/>
    <property name="KeySerializer" ref="stringRedisSerializer" />
    <property name="ValueSerializer" ref="stringRedisSerializer" />
    <property name="hashKeySerializer" ref="stringRedisSerializer"/>
    <property name="hashValueSerializer" ref="jdkRedisSerializer"/>
    <property name="enableTransactionSupport" value="true"/>
</bean>

3.3 config方式配置

@Configuration
@EnableCaching
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfig extends CachingConfigurerSupport{
    private String host;
    private int port;
    private int timeout;
    @Bean
    public KeyGenerator wiselyKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setTimeout(timeout); //设置连接超时时间
        return factory;
    }
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        return cacheManager;
    }
    @Bean
    public RedisTemplate<String, String> redisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
        template.setValueSerializer(new StringRedisSerializer());
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new JdkSerializationRedisSerializer());
        return template;
    }

}

3.4 redis 使用 

@Service
public  class GeneratorCode {

    @Autowired
    protected RedisTemplate redisTemplate;

    @Autowired
    private ISysConfigService sysConfigService;
    /**
     * 生成通用编号
     *
     * @param myCode the my code
     * @return the string
     */
    public  String generatorCommonCode(String myCode){
        String key = "sps_order_code";
        String sys_key = "order:totalCode";
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String flowCode = (String)valueOperations.get(key);
        Long value = Long.valueOf(0);
        if(flowCode==null){
            String item = sysConfigService.getValueByKey(sys_key);
            valueOperations.set(key, item);
        }else{
            value = Long.valueOf(flowCode)+1;
            valueOperations.increment(key, 1);
            sysConfigService.updateSysConfig(sys_key,value.toString());
        }
        String code = Long.valueOf(DateUtils.getUnixTimestamp()+value.longValue()).toString();
        return code;
    }

}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部