Redis spring usage summary

1.1  Introduction to Redis

 redis is a key-value storage system. Similar to Memcached, it supports relatively more value types to be stored, including string (string), list (linked list), set (collection), zset (sorted set – ordered collection) and hash (hash type). These data types all support push/pop, add/remove, intersection union and difference, and richer operations, and these operations are atomic. On this basis, redis supports sorting in various ways. Like memcached, data is cached in memory to ensure efficiency. The difference is that redis will periodically write the updated data to disk or write the modification operation to the appended record file, and on this basis realize master-slave (master-slave) synchronization.

The Redis database is completely in-memory and uses disk only for persistence. Compared to many key-value data stores, Redis has a richer set of data types. Redis can replicate data to any number of slave servers.

1.2  Advantages of Redis

 (1) Extremely fast: Redis is very fast, can execute about 110,000 collections per second, and about 81,000+ records per second.

(2) Supports rich data types: Redis supports most data types like lists, sets, sorted sets, and hashes that most developers already know. This makes it very easy to solve a wide variety of problems because we know which problems are better handled by the type of data it has.

(3) Operations are atomic: All Redis operations are atomic, which guarantees that if two clients access the Redis server at the same time, the updated value will be obtained.

(4) Multifunctional utility: Redis is a multifunctional tool that can be used in multiple uses such as caching, messaging, queues (Redis natively supports publish/subscribe), any short-lived data, applications such as web application sessions , page hit count, etc.

1.3  Disadvantages of Redis

 (1) Single thread

(2) Memory consumption

2.1 redis start

 If the corresponding service has been opened, let us keep it. The following example needs to use it. If it is not turned on, we command to turn it on, enter the Redis installation directory (the blogger's is C:\Program Files\Redis), and then turn it on with the following command:

redis-server  redis.windows.conf

If the startup reports an error, please check the following configuration,

3.1 maven pom configuration

<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 configuration

<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 mode configuration

@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 usage 

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

}

 

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324078682&siteId=291194637