springboot2.0整合redis-cluster集群

首先引入依赖pom

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
     <version>2.0.0.RELEASE</version>
 </dependency>

编写redis工具类

package cn.itchao.base;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
 * @author: jinchao
 * @date: 18/8/9 23:32
 * @description: redis操作工具类
 */
@Component
public class BaseRedisService {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public void set(String key, Object object, Long time) {
		// 让该方法能够支持多种数据类型存放
		if (object instanceof String) {
			setString(key, object);
		}
		// 如果存放时Set类型
		if (object instanceof Set) {
			setSet(key, object);
		}
		// 设置有效期

		if (time != null) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}

	}

	public void setString(String key, Object object) {
		if(object instanceof String){
			String value = (String) object;
			// 存放string类型
			stringRedisTemplate.opsForValue().set(key, value);
		}
	}

	public void setSet(String key, Object object) {
		Set<String> valueSet = (Set<String>) object;
		for (String string : valueSet) {
			stringRedisTemplate.opsForSet().add(key, string);
		}
	}

	public String getString(String key) {
		return stringRedisTemplate.opsForValue().get(key);
	}

	public void deleteKey(String key){
		stringRedisTemplate.delete(key);
	}

}

配置集群链接信息,在application.yml文件中配置

spring:
  application:
    name: member-server
  redis:
    database: 0
#单机版
#    host: 127.0.0.1
#    port: 6379
#    password: 123456
#      pool:
#        max-idle: 100
#        min-idle: 1
#        max-active: 1000
#        max-wait: -1
#集群版
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 10000
    cluster:
      nodes:
        - 192.168.100.131:6001
        - 192.168.100.131:6002
        - 192.168.100.131:6003
        - 192.168.100.131:6004
        - 192.168.100.131:6005
        - 192.168.100.131:6006

不懂redis集群搭建的请看:https://my.oschina.net/shxjinchao/blog/1923715

接下来就是如何使用redis了,这个很简单调用工具类即可

如下代码片段:

@RestController
public class MemberServiceImpl extends BaseApiService implements MemberService {

    @Autowired
    private BaseRedisService baseRedisService;

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public void testRedisSet(String key, String value) {
        baseRedisService.setString(key,value);
    }
}

 

转载于:https://my.oschina.net/shxjinchao/blog/1925590

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值