Redis在实战项目中的运用

Redis在实际项目中的运用

向业务逻辑中添加缓存

1.1 接口封装

把jedis封装成一些自己项目中常用的类库util类,方便自己在项目中的调用。

1.1.1 接口定义

将需要用到的函数类,抽象一个接口出来,方便看整体逻辑以及调用

jedisClient

package cn.e3mall.common.jedis;
import java.util.List;
public interface JedisClient {
	String set(String key, String value);
	String get(String key);
	Boolean exists(String key);
	Long expire(String key, int seconds);
	Long ttl(String key);
	Long incr(String key);
	Long hset(String key, String field, String value);
	String hget(String key, String field);
	Long hdel(String key, String... field);
	Boolean hexists(String key, String field);
	List<String> hvals(String key);
	Long del(String key);
}

JedisClientPool

package cn.e3mall.common.jedis;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class JedisClientPool implements JedisClient {
	private JedisPool jedisPool;
	public JedisPool getJedisPool() {
		return jedisPool;
	}
	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}
	@Override
	public String set(String key, String value) {
		Jedis jedis = jedisPool.getResource();
		String result = jedis.set(key, value);
		jedis.close();
		return result;
	}
	@Override
	public String get(String key) {
		Jedis jedis = jedisPool.getResource();
		String result = jedis.get(key);
		jedis.close();
		return result;
	}
	@Override
	public Boolean exists(String key) {
		Jedis jedis = jedisPool.getResource();
		Boolean result = jedis.exists(key);
		jedis.close();
		return result;
	}
	@Override
	public Long expire(String key, int seconds) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.expire(key, seconds);
		jedis.close();
		return result;
	}
	@Override
	public Long ttl(String key) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.ttl(key);
		jedis.close();
		return result;
	}
	@Override
	public Long incr(String key) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.incr(key);
		jedis.close();
		return result;
	}
	@Override
	public Long hset(String key, String field, String value) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.hset(key, field, value);
		jedis.close();
		return result;
	}
	@Override
	public String hget(String key, String field) {
		Jedis jedis = jedisPool.getResource();
		String result = jedis.hget(key, field);
		jedis.close();
		return result;
	}
	@Override
	public Long hdel(String key, String... field) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.hdel(key, field);
		jedis.close();
		return result;
	}
	@Override
	public Boolean hexists(String key, String field) {
		Jedis jedis = jedisPool.getResource();
		Boolean result = jedis.hexists(key, field);
		jedis.close();
		return result;
	}
	@Override
	public List<String> hvals(String key) {
		Jedis jedis = jedisPool.getResource();
		List<String> result = jedis.hvals(key);
		jedis.close();
		return result;
	}
	@Override
	public Long del(String key) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.del(key);
		jedis.close();
		return result;
	}
}

JedisClientCluster

package cn.e3mall.common.jedis;
import java.util.List;
import redis.clients.jedis.JedisCluster;
public class JedisClientCluster implements JedisClient {
	private JedisCluster jedisCluster;
	public JedisCluster getJedisCluster() {
		return jedisCluster;
	}
	public void setJedisCluster(JedisCluster jedisCluster) {
		this.jedisCluster = jedisCluster;
	}
	@Override
	public String set(String key, String value) {
		return jedisCluster.set(key, value);
	}
	@Override
	public String get(String key) {
		return jedisCluster.get(key);
	}
	@Override
	public Boolean exists(String key) {
		return jedisCluster.exists(key);
	}
	@Override
	public Long expire(String key, int seconds) {
		return jedisCluster.expire(key, seconds);
	}
	@Override
	public Long ttl(String key) {
		return jedisCluster.ttl(key);
	}
	@Override
	public Long incr(String key) {
		return jedisCluster.incr(key);
	}
	@Override
	public Long hset(String key, String field, String value) {
		return jedisCluster.hset(key, field, value);
	}
	@Override
	public String hget(String key, String field) {
		return jedisCluster.hget(key, field);
	}
	@Override
	public Long hdel(String key, String... field) {
		return jedisCluster.hdel(key, field);
	}
	@Override
	public Boolean hexists(String key, String field) {
		return jedisCluster.hexists(key, field);
	}
	@Override
	public List<String> hvals(String key) {
		return jedisCluster.hvals(key);
	}
	@Override
	public Long del(String key) {
		return jedisCluster.del(key);
	}
}

配置:applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
	
	<!-- 连接redis单机版 -->
	<bean id="jedisClientPool" class="cn.e3mall.common.jedis.JedisClientPool">
		<property name="jedisPool" ref="jedisPool"></property>
	</bean>
	<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
		<constructor-arg name="host" value="115.159.126.205"/>
		<constructor-arg name="port" value="6379"/>
	</bean>
	<!-- 连接redis集群 -->
	<!-- <bean id="jedisClientCluster" class="cn.e3mall.common.jedis.JedisClientCluster">
		<property name="jedisCluster" ref="jedisCluster"/>
	</bean>
	<bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">
		<constructor-arg name="nodes">
			<set>
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg name="host" value="192.168.25.162"></constructor-arg>
					<constructor-arg name="port" value="7001"></constructor-arg>
				</bean> 
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg name="host" value="192.168.25.162"></constructor-arg>
					<constructor-arg name="port" value="7002"></constructor-arg>
				</bean> 
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg name="host" value="192.168.25.162"></constructor-arg>
					<constructor-arg name="port" value="7003"></constructor-arg>
				</bean> 
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg name="host" value="192.168.25.162"></constructor-arg>
					<constructor-arg name="port" value="7004"></constructor-arg>
				</bean> 
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg name="host" value="192.168.25.162"></constructor-arg>
					<constructor-arg name="port" value="7005"></constructor-arg>
				</bean> 
				<bean class="redis.clients.jedis.HostAndPort">
					<constructor-arg name="host" value="192.168.25.162"></constructor-arg>
					<constructor-arg name="port" value="7006"></constructor-arg>
				</bean> 
			</set>
		</constructor-arg>
	</bean> -->
</beans>

封装代码测试

@Test
public void JedisClient() throws Exception {
	//初始化Spring容器
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-redis.xml");
	//从容器中获得JedisClient对象
	JedisClient jedisClient = applicationContext.getBean(JedisClient.class);
	jedisClient.set("first", "100");
	String result = jedisClient.get("first");
	System.out.println(result);						
}

添加缓存

查询内容列表时添加缓存

  1. 查询数据库之前先查询缓存
  2. 查询到结果直接响应结果
  3. 查询不到,缓存中没有需要的数据查询数据库
  4. 数据库将查询到的结果添加到缓存中
  5. 返回查询结果

== 注意:添加缓存不能影响正常业务逻辑==

代码层实现

注入jedis

@Autowired
private JedisClient jedisClient;

添加新内容

@Value("${CONTENT_LIST}")
private String CONTENT_LIST;
	
@Override
public E3Result addContent(TbContent content) {
	//将内容数据插入到内容表
	content.setCreated(new Date());
	content.setUpdated(new Date());
	//插入到数据库
	contentMapper.insert(content);
	//缓存同步,删除缓存中对应的数据。
	jedisClient.hdel(CONTENT_LIST, content.getCategoryId().toString());
	return E3Result.ok();
}

** 查询对应值**

@Override
public List<TbContent> getContentListByCid(long cid) {
	//查询缓存
	try {
		//如果缓存中有直接响应结果
		String json = jedisClient.hget(CONTENT_LIST, cid + "");
		if (StringUtils.isNotBlank(json)) {
			List<TbContent> list = JsonUtils.jsonToList(json,TbContent.class);
			System.out.println("从缓存中查出的数据");
			return list;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	//如果没有查询数据库
	TbContentExample example = new TbContentExample();
	Criteria criteria = example.createCriteria();
	//设置查询条件
	criteria.andCategoryIdEqualTo(cid);
	//执行查询
	List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example);
	//把结果添加到缓存
	try {
		System.out.println("把结果添加到缓存");
		jedisClient.hset(CONTENT_LIST, cid + "", JsonUtils.objectToJson(list));
	} catch (Exception e) {
		e.printStackTrace();
	}
	return list;
}

注意:要实现缓存同步
热缓存,可以给他设置一个过期时间(不同步也是可以的)

        @Override
	public TbItem getItemById(long itemId) {
		//获取商品添加缓存,不影业务响逻辑,try-catch
		try {
			System.out.println("缓存获取商品信息");
			String json = jedisClient.get(REDIS_ITEM_PRE+":"+itemId+":BASE");
			if(StringUtils.isNotBlank(json)) {
				TbItem tbItem = JsonUtils.jsonToPojo(json,TbItem.class);
				return tbItem;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		//缓存中没有,查询数据库
		//根据主键查询
		//TbItem tbItem = itemMapper.selectByPrimaryKey(itemId);
		TbItemExample example = new TbItemExample();
		Criteria criteria = example.createCriteria();
		//设置查询条件
		criteria.andIdEqualTo(itemId);
		//执行查询
		List<TbItem> list = itemMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			//结果添加到缓存
			try {
				System.out.println("缓存添加商品信息");
				jedisClient.set(REDIS_ITEM_PRE+":"+itemId+":BASE",JsonUtils.objectToJson(list.get(0)));
				//设置过期时间(1个小时)
				jedisClient.expire(REDIS_ITEM_PRE+":"+itemId+":BASE",TIEM_CACHE_EXPIRE);
			}catch(Exception e) {
				e.printStackTrace();
			}
			return list.get(0);
		}
		return null;
	}

以上博客来自:https://blog.csdn.net/m0_37499059/article/details/79964717
仅仅将以上博客简化为自己需要的部分,如有侵权,私聊删除!

你可能感兴趣的:(reids,实习经历,20.6.9,11.56AM,redis,实战)