spring cloud +redis整合

  • Post author:
  • Post category:其他


1、添加pom依赖文件

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.4.2</version>
        </dependency>

2、redis信息配置

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8  
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)
spring.redis.timeout=0  

3、读取配置文件

package com.jinzhu.commons.config.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.lang.reflect.Method;

/**
 * Created by rick on 2017/12/16.
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    private static Logger logger = Logger.getLogger(RedisConfig.class);
    @Bean
    public KeyGenerator keyGenerator() {
        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();
            }
        };
    }
    // @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        //rcm.setDefaultExpiration(60);//秒
        return rcm;
    }
    @Autowired
    RedisTemplate redisTemplate;
    @Bean
    public ValueOperations<String,Object> vos(){
        return redisTemplate.opsForValue();
    }
}

4、使用

RedisTemplate获取redis信息




package com.jinzhu.web.controller;

import com.jinzhu.commons.config.redis.RedisCache;
import com.jinzhu.commons.core.message.Message;
import com.jinzhu.commons.core.message.SuccessMessage;
import com.jinzhu.user.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
public class MainController {


    private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    protected RedisTemplate redisTemplate;


    @RequestMapping(value = "userinfo/get")
    @ResponseBody
    public Message getUserInfo(Long userId) {
        LOGGER.info("测试redis");
        String redisSet = "hello";
        redisTemplate.opsForValue().set("redisSet",redisSet);
        UserInfo user = new UserInfo();
        user.setUserId(userId);
        ResponseEntity<UserInfo> entity = restTemplate.postForEntity("http://JINZHU-SERVICE-PRODUCER/userinfo/get", user, UserInfo.class, new Object[]{});
        SuccessMessage message = new SuccessMessage();
        UserInfo userInfo = entity.getBody();
        Object obj = redisTemplate.opsForValue().get("redisSet");
        userInfo.setUserName(obj.toString());
        message.setData(userInfo);
        return message;
    }
}



版权声明:本文为zhangchangbin123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。