springboot 整合redis集羣

springboot整合redis集羣比較簡單,我們直接代碼說話:

一 引入依賴,配置pom.xml

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- 使用web啓動器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 使用aop模板啓動器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>
	</dependencies>

二  配置redis集羣,配置application.yml文件

server:
  port: 8081
spring:
  redis:
   cluster:
     nodes: 127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384
   max-redirects: 500
   database: 1
   timeout: 3000

三 實現代碼

redis實現類,RedisServiceImpl.class

package com.redis.cluster.servie.impl;




import com.alibaba.fastjson.JSON;
import com.redis.cluster.servie.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * Created by xiaour.github.com on 2017/11/8.
 */
@Service("redisService")
@Transactional(rollbackFor = Exception.class)
public class RedisServiceImpl implements RedisService {
    private final Logger log = LoggerFactory.getLogger(RedisServiceImpl.class);
    private static int seconds= 86400;
    @Autowired
    private RedisTemplate<String, ?> redisTemplate;
    @Override
    public boolean set(final String key, final String value) throws RuntimeException {
        log.info(key,"Key is not empty.");
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
        });
        return result;
    }
    @Override
    public String get(final String key) throws RuntimeException {
        log.info(key,"Key is not empty.");
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] value =  connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    @Override
    public void del(final String key) throws RuntimeException {
        log.info(key,"Key is not empty.");
        redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection conn) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                return conn.del(serializer.serialize(key));
            }
        });
    }


    @Override
    public boolean expire(final String key, long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    @Override
    public boolean setexpire(String key, String value, long expire) throws RuntimeException {
        log.info(key,"Key is not empty.");
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                if(expire > 0){
                    connection.expire(serializer.serialize(key), expire);
                }
                return true;
            }
        });
        return result;
    }


    @Override
    public boolean setObj(final String key, Object obj, long expire)throws RuntimeException {
        Assert.hasText(key,"Key is not empty.");
        final String value = JSON.toJSONString(obj);
        Boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                if(expire > 0){
                    connection.expire(serializer.serialize(key), expire);
                }
                return true;
            }
        });
        return result;
    }

    @Override
    public <T> T getObj(String key, Class<T> clz) throws RuntimeException {
        String value = this.get(key);
        if(value == null){
            return null;
        }
        return  JSON.parseObject(value,clz);
    }


}

接口:RedisController.class

package com.redis.cluster.web;

import com.redis.cluster.servie.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Administrator on 2018/10/25.
 */
@RestController
@RequestMapping("/api/redis")
public class RedisController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisService redisService;

    @GetMapping("/set/{key}/{value}")
    public String set(
            @PathVariable("key")  String key ,
            @PathVariable("value") String value){
        redisService.set(key,value);
        return "ok";
    }

    @GetMapping("/get/{key}")
    public String get(
            @PathVariable("key")  String key ){
        return  redisService.get(key);
    }
}

四 測試:

設置值

獲取值

redis控制檯:

github地址:https://github.com/hxf044/redisCluster

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章