在SpringBoot项目中需要连接两个Redis实例,并实现从A中获取数据并存取到B中。
另外A中redis的地址和密码不能外漏,则将A的地址和密码写在jar包中,B中redis参数可以在外置
配置文件application.yml中进行动态配置。
注:
博客:
BADAO_LIUMANG_QIZHI的博客_霸道流氓气质_CSDN博客
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
1、新建SpringBoot项目并添加依赖
redis.clients jedis3.3.0 org.springframework.data spring-data-redis2.3.6.RELEASE com.alibaba fastjson1.2.75
2、完整的pom文件代码
4.0.0 org.springframework.boot spring-boot-starter-parent2.3.7.RELEASE com.example demo0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-testtest redis.clients jedis3.3.0 org.springframework.data spring-data-redis2.3.6.RELEASE com.alibaba fastjson1.2.75 org.springframework.boot spring-boot-maven-plugin
3、在配置文件application.properties中配置B的redis的参数
server.port=9090 spring.redis.user.host=另一个redis的地址 spring.redis.user.port=6379 spring.redis.user.password=123456
4、新建Redis的配置类
package com.example.demo.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypevalidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
//order
@Value("127.0.0.1")
private String orderHost;
@Value("6379")
private String orderPort;
@Value("123456")
private String orderPassword;
//user
@Value("${spring.redis.user.host}")
private String userHost;
@Value("${spring.redis.user.port}")
private String userPort;
@Value("${spring.redis.user.password}")
private String userPassword;
private static final int MAX_IDLE = 200; //最大空闲连接数
private static final int MAX_TOTAL = 1024; //最大连接数
private static final long MAX_WAIT_MILLIS = 10000; //建立连接最长等待时间
//配置工厂
public RedisConnectionFactory connectionFactory(String host, int port, String password,int index) {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
redisStandaloneConfiguration.setPassword(password);
redisStandaloneConfiguration.setDatabase(index);
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
//连接池配置
public JedisPoolConfig poolConfig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxWaitMillis(maxWaitMillis);
poolConfig.setTestonBorrow(testOnBorrow);
return poolConfig;
}
@Bean("redisTemplateOrder")
public RedisTemplate
注意:
这里连接的是两个Redis,其中A的Redis命名为order,其参数直接在注解中固定赋值。
B的Redis命名为user,参数从配置文件中获取。
这其中又用到了FastJson进行序列化的工具类FastJson2JsonRedisSerializer
package com.example.demo.config; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import org.springframework.util.Assert; import java.nio.charset.Charset; public class FastJson2JsonRedisSerializerimplements RedisSerializer { @SuppressWarnings("unused") private ObjectMapper objectMapper = new ObjectMapper(); public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class clazz; static { ParserConfig.getGlobalInstance().setAutoTypeSupport(true); } public FastJson2JsonRedisSerializer(Class clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSonString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return JSON.parseObject(str, clazz); } public void setObjectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "'objectMapper' must not be null"); this.objectMapper = objectMapper; } protected JavaType getJavaType(Class> clazz) { return TypeFactory.defaultInstance().constructType(clazz); } }
5、分别新建两个Redis进行读取操作的service类
RedisServiceOrder:
package com.example.demo;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisServiceOrder
{
@Resource(name = "redisTemplateOrder")
public RedisTemplate redisTemplate;
public void setCacheObject(final String key, final T value)
{
redisTemplate.opsForValue().set(key, value);
}
public void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit)
{
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
public boolean expire(final String key, final long timeout)
{
return expire(key, timeout, TimeUnit.SECONDS);
}
public boolean expire(final String key, final long timeout, final TimeUnit unit)
{
return redisTemplate.expire(key, timeout, unit);
}
public T getCacheObject(final String key)
{
ValueOperations operation = redisTemplate.opsForValue();
return operation.get(key);
}
public boolean deleteObject(final String key)
{
return redisTemplate.delete(key);
}
public long deleteObject(final Collection collection)
{
return redisTemplate.delete(collection);
}
public long setCacheList(final String key, final List dataList)
{
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
public List getCacheList(final String key)
{
return redisTemplate.opsForList().range(key, 0, -1);
}
public long setCacheSet(final String key, final Set dataSet)
{
Long count = redisTemplate.opsForSet().add(key, dataSet);
return count == null ? 0 : count;
}
public Set getCacheSet(final String key)
{
return redisTemplate.opsForSet().members(key);
}
public void setCacheMap(final String key, final Map dataMap)
{
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
public Map getCacheMap(final String key)
{
return redisTemplate.opsForHash().entries(key);
}
public void setCacheMapValue(final String key, final String hKey, final T value)
{
redisTemplate.opsForHash().put(key, hKey, value);
}
public T getCacheMapValue(final String key, final String hKey)
{
HashOperations opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
public List getMultiCacheMapValue(final String key, final Collection hKeys)
{
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
public Collection keys(String pattern)
{
return redisTemplate.keys(pattern);
}
public List getCacheList(Set keys) {
return redisTemplate.opsForValue().multiGet(keys);
}
}
RedisServiceUser:
package com.example.demo;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisServiceUser
{
@Resource(name = "redisTemplateUser")
public RedisTemplate redisTemplate;
public void setCacheObject(final String key, final T value)
{
redisTemplate.opsForValue().set(key, value);
}
public void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit)
{
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
public boolean expire(final String key, final long timeout)
{
return expire(key, timeout, TimeUnit.SECONDS);
}
public boolean expire(final String key, final long timeout, final TimeUnit unit)
{
return redisTemplate.expire(key, timeout, unit);
}
public T getCacheObject(final String key)
{
ValueOperations operation = redisTemplate.opsForValue();
return operation.get(key);
}
public boolean deleteObject(final String key)
{
return redisTemplate.delete(key);
}
public long deleteObject(final Collection collection)
{
return redisTemplate.delete(collection);
}
public long setCacheList(final String key, final List dataList)
{
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
public List getCacheList(final String key)
{
return redisTemplate.opsForList().range(key, 0, -1);
}
public long setCacheSet(final String key, final Set dataSet)
{
Long count = redisTemplate.opsForSet().add(key, dataSet);
return count == null ? 0 : count;
}
public Set getCacheSet(final String key)
{
return redisTemplate.opsForSet().members(key);
}
public void setCacheMap(final String key, final Map dataMap)
{
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
public Map getCacheMap(final String key)
{
return redisTemplate.opsForHash().entries(key);
}
public void setCacheMapValue(final String key, final String hKey, final T value)
{
redisTemplate.opsForHash().put(key, hKey, value);
}
public T getCacheMapValue(final String key, final String hKey)
{
HashOperations opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
public List getMultiCacheMapValue(final String key, final Collection hKeys)
{
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
public Collection keys(String pattern)
{
return redisTemplate.keys(pattern);
}
public List getCacheList(Set keys) {
return redisTemplate.opsForValue().multiGet(keys);
}
}
6、编写测试Controller进行测试
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/badao")
public class TestController {
@Autowired
private RedisServiceOrder redisServiceOrder;
@Autowired
private RedisServiceUser redisServiceUser;
@GetMapping("/test")
public String list()
{
redisServiceOrder.setCacheObject("badao","公众号:霸道的程序猿");
String badao = redisServiceOrder.getCacheObject("badao");
redisServiceUser.setCacheObject("copyBadao",badao);
return "公众号:霸道的程序猿";
}
}
7、启动项目并调用测试接口



