Redis 和 SpringDataRedis

redis分布式缓存

redis底层使用C语言编写, 存储数据是放在内存中, 速度非常快.

作用:

redis在互联网项目中一般充当分布式缓存使用

业务流程:

  1. 获取数据的时候先从redis中获取, 如果获取到数据则直接返回, 就不用访问数据库了
  2. 如果获取不到数据, 可以从数据库中查询, 查询到后放入redis中一份, 下回就可以直接从redis中查询到这样大大降低了数据库的高并发访问压力.

持久化方案:

a) rdb(默认) 分时持久化

可以在配置文件中设定, 多长时间持久化一次, 持久化次数少也就是操作硬盘的次数少, 速度快. 但是如果在没有完成持久化前,服务器断电, 则内存中没有持久化的数据会丢失.

b) aof 实时持久化

每次向redis中做增删改操作, 都会将数据持久化到硬盘上, 数据可靠性高, 不会丢失, 但是速度慢

redis中数据类型: string, set, zset, list, hash

redis同类型技术:

memcache是redis的同类型技术, 底层也是使用c语言编写, 现在memcache已经被redis替代了.
memcache的速度和redis相当. 但是memcache没有持久化方式.

mongodb和redis区别:

  1. mongodb也是一个nosql数据库, 存储的数据是非结构化的, 但是mongdb和redis不能放在一起对比,
    因为完全没有可比性, 使用场景完全不同
  2. redis: 主要使用内存, 有两种持久化方案, 速度非常快, 一般做分布式缓存使用
  3. mongodb: 主要使用硬盘存储, 所以不会担心数据丢失, 速度介于redis和传统数据库之间.但是mongodb更擅长存储大文本数据, 以及一些非结构化数据, mongodb比redis的数据类型更加丰富.例如: 存储小说网站的小说, 存储电商网站的评论等这些数据。
    (所以它更像是对传统数据库的一种补充)

redis中的五大数据类型:

string:  字符串
hash:	相当于map, 是一种键值对形式, 存入的数据是无序的, key不可以重复
list:	存入其中的数据是有序的, 存入其中的数据可以重复
set:	存入其中的数据是无序的, 存入其中的数据不可以重复
zset:	存入其中的数据是有序的, 存入其中的数据不可以重复

Spring Data Redis

spring家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装RedisTemplate提供了redis各种操作、异常处理及序列化等。

spring-data-redis针对jedis提供了如下功能:

  1. 连接池自动管理,提供了一个高度封装的“RedisTemplate”类
  2. 针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口

ValueOperations: 简单K-V操作(String)
SetOperations: set类型数据操作
ZSetOperations:zset类型数据操作
HashOperations:针对map类型的数据操作
ListOperations:针对list类型的数据操作

Demo

一、导包

注意要引入jedis,因为spring-data-redis是对jedis基础上的进一步封装。

二、配置文件

(1)redis-config.properties(将连接redis的地址端口和连接数抽出成一个文件)

redis.host=192.168.200.128
redis.port=6379
redis.pass=
redis.database=0
redis.maxIdle=300
redis.maxWait=3000
redis.testOnBorrow=true

(2)applicationContext-redis.xml(引入redis-config.properties)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath*:*.properties" />
    <!-- redis 相关配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>
    <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory" />
    </bean>
</beans>

三、常用数据类型操作

/**
*操作String类型
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-redis.xml"})
public class TestString {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testSet() {
        redisTemplate.boundValueOps("testKey").set("xxxxxxx");
    }

    @Test
    public void testGet() {
        String testKey = (String) redisTemplate.boundValueOps("testKey").get();
        System.out.println("======" + testKey);
    }

    @Test
    public void testDelete() {
        redisTemplate.delete("testKey");
    }
}
/**
 * 演示存取删除hash, hash类型是无序的
 * 整个redis就相当于一个大的hashmap
 * key      value
 *          如果value是hash类型, 那么value也相当于一个HashMap
 * testkey1         field        value
 *                  001         张三
 *                  002         李四
 * testkey2
 *                  001         青龙
 *                  002         白虎
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-redis.xml"})
public class TestHash {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testPut() {
        redisTemplate.boundHashOps("testHash").put("001", "青龙");
        redisTemplate.boundHashOps("testHash").put("002", "白虎");
        redisTemplate.boundHashOps("testHash").put("003", "朱雀");
        redisTemplate.boundHashOps("testHash").put("004", "玄武");
    }

    @Test
    public void testGetOne() {
        String value = (String)redisTemplate.boundHashOps("testHash").get("003");
        System.out.println("======" + value);
    }

    @Test
    public void testGetAll() {
        Map<String, String> testHash = (Map<String, String>)redisTemplate.boundHashOps("testHash").entries();
       		//Map不能遍历,所以提供entrySet()方法转成集合遍历
        Set<Map.Entry<String, String>> entries = testHash.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println("====key===" + entry.getKey());
            System.out.println("====value===" + entry.getValue());
        }
    }

    @Test
    public void testDeleteOne() {
        redisTemplate.boundHashOps("testHash").delete("003");
    }

    @Test
    public void testDeleteAll() {
        redisTemplate.delete("testHash");
    }
}

在这里插入图片描述

/**
 * 演示list类型
 * redis相当于一个大的hashMap
 * key      value
 *          演示list类型其实就是演示value就是一个List集合
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-redis.xml"})
public class TestList {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testLpush() {
        redisTemplate.boundListOps("testList").leftPush("001");
        redisTemplate.boundListOps("testList").leftPush("002");
        redisTemplate.boundListOps("testList").leftPush("003");
        redisTemplate.boundListOps("testList").leftPush("004");
    }

    @Test
    public void testRpush() {
        redisTemplate.boundListOps("testList").rightPush("001");
        redisTemplate.boundListOps("testList").rightPush("002");
        redisTemplate.boundListOps("testList").rightPush("003");
        redisTemplate.boundListOps("testList").rightPush("004");
    }

    @Test
    public void testRange() {
        List<String> testList = redisTemplate.boundListOps("testList").range(0, 10);
        for (String s : testList) {
            System.out.println("======" + s);
        }
    }

    @Test
    public void testDelete() {
        redisTemplate.delete("testList");
    }
}

Redis做广告缓存案例

1、页面发送请求到web层

@RestController
@RequestMapping("/content")
public class ContentController {

    @Reference
    private ContentService contentService;

    @RequestMapping("/findByCategoryId")
    public List<Content> findByCategoryId(Long categoryId) {
        List<Content> list = contentService.findByCategoryIdFromRedis(categoryId);
        return list;
    }
}

2、web调用service实现广告CRUD

/**
 * 使用redis分布式缓存原则:
 * 一般关系型数据库作为我们的主数据库存储数据, 如果涉及到使用分布式缓存redis, 要保证redis中的数据
 * 和数据库中的数据要一致.
 */
@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private ContentDao contentDao;

    @Autowired
    private RedisTemplate redisTemplate;

 /**
     * 整个redis相当于一个大的hashMap, 在这个map中key是不可以重复的, 所以key是稀缺资源
     * key      value(value使用hash类型因为可以尽量少的占用key)
     *          field           value
     *          分类id            对应的这个分类的广告集合数据List<Content>
     *            001               List<Content>
     *            002               List<Content>
     */
    @Override
    public List<Content> findByCategoryIdFromRedis(Long categoryId) {
        //1. 首先根据分类id到redis中获取数据
        List<Content> contentList = (List<Content>)redisTemplate.boundHashOps(Constants.CONTENT_LIST_REDIS).get(categoryId);
        //2. 如果redis中没有数据则到数据库中获取数据
        if (contentList == null) {
            //3. 如果数据库中获取到数据, 则放入redis中一份
            contentList = findByCategoryId(categoryId);
            redisTemplate.boundHashOps(Constants.CONTENT_LIST_REDIS).put(categoryId, contentList);
        }
        return contentList;
    }

    public List<Content> findByCategoryId(Long categoryId) {
        ContentQuery query = new ContentQuery();
        ContentQuery.Criteria criteria = query.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        List<Content> list = contentDao.selectByExample(query);
        return list;
    }

   @Override
    public void add(Content content) {
        //1. 将新广告添加到数据库中
        contentDao.insertSelective(content);
        //2. 根据分类id, 到redis中删除对应分类的广告集合数据
        redisTemplate.boundHashOps(Constants.CONTENT_LIST_REDIS).delete(content.getCategoryId());
    }
    
	@Override
    public void delete(Long[] ids) {
        if (ids != null) {
            for (Long id : ids) {
                //1. 根据广告id, 到数据库中查询广告对象
                Content content = contentDao.selectByPrimaryKey(id);
                //2. 根据广告对象中的分类id, 删除redis中对应的广告集合数据
                redisTemplate.boundHashOps(Constants.CONTENT_LIST_REDIS).delete(content.getCategoryId());
                //3. 根据广告id删除数据库中的广告数据
                contentDao.deleteByPrimaryKey(id);
            }
        }
    }

 	@Override
    public void update(Content content) {
        //1. 根据广告id, 到数据库中查询原来的广告对象
        Content oldContent = contentDao.selectByPrimaryKey(content.getId());
        //2. 根据原来的广告对象中的分类id, 到redis中删除对应的广告集合数据
        redisTemplate.boundHashOps(Constants.CONTENT_LIST_REDIS).delete(oldContent.getCategoryId());
        //3. 根据传入的最新的广告对象中的分类id, 删除redis中对应的广告集合数据
        redisTemplate.boundHashOps(Constants.CONTENT_LIST_REDIS).delete(content.getCategoryId());
        //4. 将新的广告对象更新到数据库中
        contentDao.updateByPrimaryKeySelective(content);
    }

发布了33 篇原创文章 · 获赞 2 · 访问量 961

猜你喜欢

转载自blog.csdn.net/Rhin0cer0s/article/details/103752419
今日推荐