POM.xml配置
添加对spring-boot-starter-data-redis及jedis的依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.szl.sample</groupId>
<artifactId>springboot-redis-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-redis-sample</name>
<description>springboot-redis-sample</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yaml配置
redis cluster配置包括nodes和重定向最大数
redis:
cluster:
nodes:
- 172.23.11.163:6379
- 172.23.11.186:6379
- 172.23.11.188:6379
maxRedirects: 3
配置RedisTemplate通过集群访问redis
RedisClusterConfigProperties类用来读取redisCluster相关配置
package com.sample.redis.config;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author szl
*
*/
@Component
@ConfigurationProperties(prefix = "redis.cluster")
public class RedisClusterConfigProperties {
/**
* master nodes
*/
private List<String> nodes;
/**
* max redirects
*/
private Integer maxRedirects = 3;
public List<String> getNodes() {
return nodes;
}
public void setNodes(List<String> nodes) {
this.nodes = nodes;
}
public Integer getMaxRedirects() {
return maxRedirects;
}
public void setMaxRedirects(Integer maxRedirects) {
this.maxRedirects = maxRedirects;
}
}
RedisClusterConfig配置RedisTemplate
package com.sample.redis.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author szl
*
*/
@SpringBootConfiguration
public class RedisClusterConfig {
@Autowired
private RedisClusterConfigProperties clusterProperties;
@Bean
public RedisClusterConfiguration getClusterConfig() {
RedisClusterConfiguration rcc = new RedisClusterConfiguration(clusterProperties.getNodes());
rcc.setMaxRedirects(clusterProperties.getMaxRedirects().intValue());
return rcc;
}
@Bean
public JedisConnectionFactory getConnectionFactory(RedisClusterConfiguration cluster) {
return new JedisConnectionFactory(cluster);
}
@Bean
public RedisTemplate getRedisTemplate(JedisConnectionFactory factory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(redisSerializer);
return redisTemplate;
}
@Bean
public StringRedisTemplate getStringRedisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate stringTemplate = new StringRedisTemplate();
stringTemplate.setConnectionFactory(factory);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
stringTemplate.setKeySerializer(redisSerializer);
stringTemplate.setHashKeySerializer(redisSerializer);
stringTemplate.setValueSerializer(redisSerializer);
return stringTemplate;
}
}
封装redis操作类
IRedisService接口定义redis的各种操作
package com.sample.redis.service;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
/**
* @author szl
*
*/
public interface IRedisService {
/**
* get object form redis by key
*
* @param key
* @return
*/
public Object getObject(String key);
/**
* get class by key
*
* @param key
* @param requiredType
* @return
*/
public <T> T get(String key, Class<? extends Serializable> requiredType);
/**
* remove key
*
* @param key
* @return
*/
public boolean remove(String key);
/**
* @param key
* @param object
* @return
*/
public void saveObject(String key, Serializable object);
/**
* @param key
* @param object
* @param timeout
* @param unit
* @return
*/
public void saveWithExpireTime(String key, Serializable object, long timeout, TimeUnit unit);
/**
* @param key
* @return
*/
public boolean hasKey(String key);
}
实现上面接口
package com.sample.redis.service.impl;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.sample.redis.service.IRedisService;
/**
* @author szl
*
*/
@Service
public class RedisServiceImpl implements IRedisService {
@Autowired
private RedisTemplate<Serializable, Serializable> redisTemplate;
@Override
public Object getObject(String key) {
return redisTemplate.opsForValue().get(key);
}
@SuppressWarnings("unchecked")
@Override
public <T> T get(String key, Class<? extends Serializable> requiredType) {
Serializable val = redisTemplate.opsForValue().get(key);
if(val == null){
return null;
}
return ((T)val);
}
@Override
public boolean remove(String key) {
return redisTemplate.delete(key);
}
@Override
public void saveObject(String key, Serializable object) {
redisTemplate.opsForValue().set(key, object);
}
@Override
public void saveWithExpireTime(String key, Serializable object, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, object, timeout, unit);
}
@Override
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
}
编写启动类
这里为了看到效果,继承了CommandLineRunner,实际应用中去掉即可
package com.sample.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.sample.redis.service.IRedisService;
/**
* @author szl
*
*/
@SpringBootApplication
public class Application implements CommandLineRunner{
@Autowired
private IRedisService service;
public static void main(String[] args) {
SpringApplication.run(Application.class, args).close();
}
@Override
public void run(String... args) throws Exception {
boolean hasName = service.hasKey("name");
System.out.println("=======================================");
System.out.println("Is redis has a 'neme' key? -> "+hasName);
service.saveObject("name", "Hello redis cluster");
hasName = service.hasKey("name");
System.out.println("After add key 'name', Is redis has a 'neme' key? -> "+hasName);
if(hasName){
String val = service.get("name", String.class);
System.out.println("The value of key 'neme' is "+val);
}
service.remove("name");
hasName = service.hasKey("name");
System.out.println("After remove the 'name' key , is redis has a 'neme' key? -> "+hasName);
System.out.println("=======================================");
}
}
至此,Spring Boot+spring-data-redis访问redis集群的代码已写完,运行后效果如下,具体项目代码可到git下载https://github.com/sunzheng04/springboot-redis-cluster-sample
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.RELEASE)
2018-03-09 14:52:17.578 INFO 9756 --- [ main] com.sample.redis.Application : Starting Application on szl-HP with PID 9756 (C:\Users\szl\workspace\Springboot-rediscluster\target\classes started by szl in C:\Users\szl\workspace\Springboot-rediscluster)
2018-03-09 14:52:17.580 INFO 9756 --- [ main] com.sample.redis.Application : No active profile set, falling back to default profiles: default
2018-03-09 14:52:17.611 INFO 9756 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3bd82cf5: startup date [Fri Mar 09 14:52:17 CST 2018]; root of context hierarchy
2018-03-09 14:52:17.889 INFO 9756 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2018-03-09 14:52:18.218 INFO 9756 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService
2018-03-09 14:52:18.586 INFO 9756 --- [ main] com.sample.redis.Application : Started Application in 1.265 seconds (JVM running for 1.541)
=======================================
Is redis has a 'neme' key? -> false
After add key 'name', Is redis has a 'neme' key? -> true
The value of key 'neme' is Hello redis cluster
After remove the 'name' key , is redis has a 'neme' key? -> false
=======================================
2018-03-09 14:52:18.658 INFO 9756 --- [ main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3bd82cf5: startup date [Fri Mar 09 14:52:17 CST 2018]; root of context hierarchy
2018-03-09 14:52:18.671 INFO 9756 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService