Redis spring 使用总结

1.1 Redis介绍

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

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

1.2 Redis优势

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

(2)支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它很是容易解决各类各样的问题,由于咱们知道哪些问题是能够处理经过它的数据类型更好。数据库

(3)操做都是原子性:全部Redis操做是原子的,这保证了若是两个客户端同时访问的Redis服务器将得到更新后的值。windows

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

1.3 Redis缺点

 (1)单线程bash

(2)耗内存服务器

2.1 redis启动

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

redis-server  redis.windows.conf

若是启动报错,请检查如下配置,maven

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;
    }

}
相关文章
相关标签/搜索