@Test
public void testSetValue(){
redisTemplate.boundHashOps("namehash").put("a", "唐僧");
redisTemplate.boundHashOps("namehash").put("b", "悟空");
redisTemplate.boundHashOps("namehash").put("c", "八戒");
redisTemplate.boundHashOps("namehash").put("d", "沙僧");
}
@Test
public void testGetKeys(){
Set s = redisTemplate.boundHashOps("namehash").keys();
System.out.println(s);
}
@Test
public void testGetValues(){
List values = redisTemplate.boundHashOps("namehash").values();
System.out.println(values);
}
@Test
public void testGetValueByKey(){
Object object = redisTemplate.boundHashOps("namehash").get("b");
System.out.println(object);
}
@Test
public void testRemoveValueByKey(){
redisTemplate.boundHashOps("namehash").delete("c");
}
<!-- 缓存 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
@Autowired
private RedisTemplate redisTemplate;
@Override
public List<TbContent> findByCategoryId(Long categoryId) {
List<TbContent> contentList= (List<TbContent>)
redisTemplate.boundHashOps("content").get(categoryId);
if(contentList==null){
System.out.println("从数据库读取数据放入缓存");
//根据广告分类 ID 查询广告列表
TbContentExample contentExample=new TbContentExample();
Criteria criteria2 = contentExample.createCriteria();
criteria2.andCategoryIdEqualTo(categoryId);
criteria2.andStatusEqualTo("1");//开启状态
contentExample.setOrderByClause("sort_order");//排序
contentList = contentMapper.selectByExample(contentExample);//获取广告列
表
redisTemplate.boundHashOps("content").put(categoryId, contentList);//存
入缓存
}else{
System.out.println("从缓存读取数据");
}
return contentList;
}
/**
* 增加
*/
@Override
public void add(TbContent content) {
contentMapper.insert(content);
//清除缓存
redisTemplate.boundHashOps("content").delete(content.getCategoryId());
}
/**
* 修改
*/
@Override
public void update(TbContent content){
//查询修改前的分类 Id
Long categoryId =
contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();
redisTemplate.boundHashOps("content").delete(categoryId);
contentMapper.updateByPrimaryKey(content);
//如果分类 ID 发生了修改,清除修改后的分类 ID 的缓存
if(categoryId.longValue()!=content.getCategoryId().longValue()){
redisTemplate.boundHashOps("content").delete(content.getCategoryId());
}
}
/**
* 批量删除
*/
@Override
public void delete(Long[] ids) {
for(Long id:ids){
//清除缓存
Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();//广
告分类 ID
redisTemplate.boundHashOps("content").delete(categoryId);
contentMapper.deleteByPrimaryKey(id);
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |