1. 程式人生 > >Spring Cloud+Redis cluster+Spring Cache配置

Spring Cloud+Redis cluster+Spring Cache配置

專案結構

personal
 +- example
     +- cacheTest
         +- config
         |   +- RedisClusterConfig.java
         |
         +- controller
         |   +- TestController.java
         |
         +- model
         |   +- TestModel.java         |
         |
         +- service
         |   +- TestService.java
| | | +- impl | +- TestServiceImpl.java | +- Application.java

pom依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency
>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>

Redis Cluster配置

spring:
  redis:
    cluster:
      nodes: 192.168.10.33:7000,192.168.10.33:7001,192.168.10.33:7002
      timeout: 2000
      max-redirects
: 7

RedisClusterConfig.java

/**
 * 配置檔案 - Redis Cluster + Spring Cache
 * Created by xiepengcheng on 2017/9/13.
 */
@Configuration
@EnableCaching
public class RedisClusterConfig extends CachingConfigurerSupport {


    /**
     * 初始化 RedisTemplate
     * Spring 使用 StringRedisTemplate 封裝了 RedisTemplate 物件來進行對redis的各種操作,它支援所有的 redis 原生的 api。
     *
     * @param clusterNodes
     * @param timeout
     * @param redirects
     * @return
     */
    @SuppressWarnings("rawtypes")
    @Bean(name = "redisTemplate")
    public RedisTemplate redisTemplate(@Value("${spring.redis.cluster.nodes}") String clusterNodes,
                                       @Value("${spring.redis.cluster.timeout}") Long timeout,
                                       @Value("${spring.redis.cluster.max-redirects}") int redirects) {

        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(connectionFactory(getClusterConfiguration(clusterNodes, timeout, redirects)));
        setSerializer(template);

        return template;
    }

    /**
     * Redis Cluster引數配置
     *
     * @param clusterNodes
     * @param timeout
     * @param redirects
     * @return
     */
    public RedisClusterConfiguration getClusterConfiguration(String clusterNodes, Long timeout, int redirects) {
        Map<String, Object> source = new HashMap<String, Object>();
        source.put("spring.redis.cluster.nodes", clusterNodes);
        source.put("spring.redis.cluster.timeout", timeout);
        source.put("spring.redis.cluster.max-redirects", redirects);
        return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
    }


    /**
     * 連線池設定
     *
     * @param configuration
     * @return
     */
    private RedisConnectionFactory connectionFactory(RedisClusterConfiguration configuration) {
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory(configuration);
        connectionFactory.afterPropertiesSet();
        return connectionFactory;
    }

    /**
     * 序列化工具
     * 使用 Spring 提供的序列化工具替換 Java 原生的序列化工具,這樣 ReportBean 不需要實現 Serializable 介面
     *
     * @param template
     */
    private void setSerializer(StringRedisTemplate template) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
    }

    /**
     * 管理快取
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        // Number of seconds before expiration. Defaults to unlimited (0)
        cacheManager.setDefaultExpiration(600); //設定key-value超時時間,時間單位是秒。
        return cacheManager;
    }


    /**
     * 生產key的策略
     *
     * @return
     */
    @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();
            }
        };
    }
}

TestController.java

/**
 * Web層 - Test
 * Created by xiepengcheng on 2017/9/12.
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    TestService testService;

    @GetMapping("/v1/testmodel/{key}")
    public List<TestModel> getTestmodel(@PathVariable String key) {

        List<TestModel> TestModelList = testService.getTestmodel(key);

        return TestModelList;
    }

    @PutMapping("/v1/testmodel/{key}")
    public String updateTestmodel(@PathVariable String key) {
        List<TestModel> testModelList = new ArrayList<TestModel>();
        TestModel testModel = new TestModel();
        testModel.setInfo("快取測試");
        testModelList.add(testModel);
        testService.updateTestmodel(key, testModelList);

        return "OK";
    }
}

TestService.java

/**
 * 服務層介面 - Test
 * Created by xiepengcheng on 2017/9/12.
 */
public interface TestService {

    /**
     * 獲取TestModel
     *
     * @param key
     * @return
     */
    List<TestModel> getTestmodel(String key);

    /**
     * 更新TestModel
     *
     * @param key
     * @param testModelList
     * @return
     */
    List<TestModel> updateTestmodel(String key, List<TestModel> testModelList);
}

TestServiceImpl.java

/**
 * 介面實現類 - Test
 * Created by xiepengcheng on 2017/9/13.
 */
@Service
public class TestServiceImpl implements TestService {

    @Override
    @Cacheable(value = "TestmodelCache", key = "#key")
    public List<TestModel> getTestmodel(String key) {

        return new ArrayList<TestModel>();
    }

    @Override
    @CachePut(value = "TestmodelCache", key = "#key")
    public List<TestModel> updateTestmodel(String key, List<TestModel> testModelList) {

        return testModelList;
    }
}

TestModel.java

/**
 * Model - 測試
 * Created by xiepengcheng on 2017/9/12.
 */
public class TestModel {

    /**
     * 測試資訊
     */
    private String info;

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

使用PostMan工具測試

這裡寫圖片描述
這裡寫圖片描述