Redis跟Spring整合,sentinel模式

时间:2023-12-09 19:16:49

普通模式整合

一、在pom.xml中引入redis的依赖

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>

二、新建redis.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- Redis连接池配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxWaitMillis" value="${redis.maxWait}"/>
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="minIdle" value="${redis.minIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="testOnBorrow" value="true" />
</bean> <bean id="jedisShardInfo" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.host}" />
<constructor-arg index="1" value="${redis.port}" type="int" />
<!--如果redis没有设置密码,就不需要这个-->
<property name="password" value="${redis.password}" />
</bean> <!-- Redis连接 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:shardInfo-ref="jedisShardInfo"
p:poolConfig-ref="jedisPoolConfig" /> <!-- 缓存序列化方式 -->
<!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->
<bean id="keySerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
<bean id="valueSerializer" class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
<bean id="hashKeySerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<bean id="hashValueSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connectionFactory-ref="jedisConnectionFactory"
p:keySerializer-ref="keySerializer"
p:valueSerializer-ref="valueSerializer"
p:enableTransactionSupport="false"
p:hashKeySerializer-ref="hashKeySerializer"
p:hashValueSerializer-ref="hashValueSerializer"/>
</beans>

三、在spring的配置文件中引入redis.xml

<import resource="classpath*:spring/redis.xml" />

四、编写dao层

public abstract class RedisGeneratorDao<K extends Serializable, V extends Serializable> {

    @Autowired
protected RedisTemplate<K, V> redisTemplate; public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
this.redisTemplate = redisTemplate;
} /**
* 获取 RedisSerializer
*/
protected RedisSerializer<String> getRedisSerializer() {
return redisTemplate.getStringSerializer();
} }
public interface MemberDao {
public boolean add(final Member member); public boolean add(final List<Member> list); public void delete(String key); public void delete(List<String> keys); public boolean update(final Member member); public Member get(final String keyId); public void deleteStr(String key);
}
import org.burning.sport.redis.model.Member;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert; import java.util.ArrayList;
import java.util.List; @Repository("memberDao")
public class MemberDaoImpl extends RedisGeneratorDao<String, Member> implements MemberDao { /**
* 添加对象
* @param member
* @return
*/
@Override
public boolean add(final Member member) {
Boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { @Override
public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
RedisSerializer<String> serializer = getRedisSerializer();
byte[] key = serializer.serialize(member.getId());
byte[] name = serializer.serialize(member.getNickname());
return redisConnection.setNX(key, name);
}
});
return result;
} /**
* 添加集合
* @param list
* @return
*/
@Override
public boolean add(final List<Member> list) {
Assert.notEmpty(list);
Boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
RedisSerializer<String> serializer = getRedisSerializer();
for(Member member : list) {
byte[] key = serializer.serialize(member.getId());
byte[] name = serializer.serialize(member.getNickname());
return redisConnection.setNX(key, name);
} return true;
}
}, false, true);
return false;
} /**
* 删除对象 ,依赖key
* @param key
*/
@Override
public void delete(String key) {
List<String> list = new ArrayList<String>();
list.add(key);
delete(list);
} /**
* 删除字符串
* @param key
*/
@Override
public void deleteStr(String key) {
redisTemplate.delete(key);
} /**
* 删除集合 ,依赖key集合
* @param keys
*/
@Override
public void delete(List<String> keys) {
redisTemplate.delete(keys);
} /**
* 修改对象
* @param member
* @return
*/
@Override
public boolean update(final Member member) {
String key = member.getId();
if(get(key) == null) {
throw new NullPointerException("数据行不存在, key = " + key);
} Boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
RedisSerializer<String> serializer = getRedisSerializer();
byte[] key = serializer.serialize(member.getId());
byte[] value = serializer.serialize(member.getNickname());
redisConnection.setNX(key, value);
return true;
}
});
return result;
} /**
* 根据key获取对象
* @param keyId
* @return
*/
@Override
public Member get(final String keyId) {
Member result = redisTemplate.execute(new RedisCallback<Member>() {
@Override
public Member doInRedis(RedisConnection redisConnection) throws DataAccessException {
RedisSerializer<String> serializer = getRedisSerializer();
byte[] key = serializer.serialize(keyId);
byte[] value = redisConnection.get(key);
if(value == null) {
return null;
} String nickName = serializer.deserialize(value);
return new Member(keyId, nickName);
}
}); return result;
}
}

五、编写service层

public interface MemberService {
/**
* 添加对象
*/
public boolean add(final Member member); /**
* 添加集合
*/
public boolean add(final List<Member> list);
/**
* 删除对象 ,依赖key
*/
public void delete(String key); /**
* 删除字符串,依赖key
* @param key
*/
public void deleteStr(String key);
/**
* 删除集合 ,依赖key集合
*/
public void delete(List<String> keys); /**
* 修改对象
*/
public boolean update(final Member member);
/**
* 根据key获取对象
*/
public Member get(final String keyId); }
@Service("memberService")
public class MemberServicefImpl implements MemberService { @Autowired
private MemberDao memberDao; @Override
public boolean add(Member member) {
return memberDao.add(member);
} @Override
public boolean add(List<Member> list) {
return memberDao.add(list);
} @Override
public void delete(String key) {
memberDao.delete(key);
} @Override
public void deleteStr(String key) {
memberDao.deleteStr(key);
} @Override
public void delete(List<String> keys) {
memberDao.delete(keys);
} @Override
public boolean update(Member member) {
return memberDao.update(member);
} @Override
public Member get(String keyId) {
return memberDao.get(keyId);
}
}

六、写测试类进行测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
public class RedisTest { @Autowired
private MemberService memberService; @Test
public void redisAddMember() {
Member member = new Member();
member.setId("1");
member.setNickname("ls"); memberService.add(member);
} @Test
public void redisDeleteStr() {
memberService.deleteStr("1");
} }

哨兵模式(sentinel)

就一个配置文件独特一点 redis-sentinel.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!--redis 哨兵模式(sentinel) 配置-->
<bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<property name="master">
<bean class="org.springframework.data.redis.connection.RedisNode">
<property name="name" value="mymaster" />
</bean>
</property>
<property name="sentinels">
<set>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg index="0" value="10.6.1**.**6" /><!--ip-->
<constructor-arg index="1" value="9980" /><!--port-->
</bean>
<bean class="org.springframework.data.redis.connection.RedisNode">
<constructor-arg index="0" value="10.6.1**.**4" /><!--ip-->
<constructor-arg index="1" value="9980" /><!--port-->
</bean>
</set>
</property>
</bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg ref="redisSentinelConfiguration"/>
</bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" value="jedisConnectionFactory" />
</bean>
</beans>

https://gitee.com/play-happy/base-project