Redis 与 SpringBoot实战及笔记

 redis的hash数据结构

可理解为HashMap<String,HashMap<String,Object>>

=> id = 1    User1

     id = 2    User2 ...

Windows启动Redis服务

cmd打开Redis的文件夹目录

服务端启动:

redis-server.exe redis.windows.conf

客户端启动:

Redis-cli

springboot 整合 redis

application.properties

#Redis服务器地址
spring.redis.host=120.24.202.14
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认位0)
spring.redis.database=0
#连接超时时间(毫秒)
spring.redis.timeout=1800000
#连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
#最大阻塞等待时间(复数表示没有限制)
spring.redis.lettuce.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
#连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0

RedisConfig

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
//key序列化方式
        template.setKeySerializer(redisSerializer);
//value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
             .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- spring2.X集成redis所需common-pool2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.11.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.4</version>
        </dependency>
    </dependencies>

springboot项目实战redis

        引入pom.xml文件    配置文件 application.yml

        具体demo代码

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    //设置Key
    public static final String USER_KEY = "USER_KEY";

    /**
     * redisTest
     * @return
     */
    //@AuthAccess
    @GetMapping("/findAllUser")
    public Result findAllUser() {
        //从redis获取缓存
        String jsonStr = stringRedisTemplate.opsForValue().get(USER_KEY);
        List<User> userList;
        if (StrUtil.isBlank(jsonStr)){
            //缓存为空 , 从数据库取出数据
            userList = userService.list();
            //存到redis中
            stringRedisTemplate.opsForValue().set(USER_KEY,JSONUtil.toJsonStr(userList));
        }else {
            //从redis获取
            userList = JSONUtil.toBean(jsonStr, new TypeReference<List<User>>() {
            }, true);
        }
        return ResultGenerator.genSuccessResult(200,userList,"获取用户信息成功!");
    }

    /**
     * 删除缓存
     * 增删改更新数据库时,调用此方法
     * @param key
     */
    private void flushRedis(String key){
        stringRedisTemplate.delete(key);
    }

使用zset数据结构实现排行榜

/**
 * @author 刘宇浩
 */
@RestController
public class WeiBoController {
    @Autowired
    private RedisTemplate redisTemplate;

    public static final String SCORE_KEY = "WeiBoScore";

    public void init(){
        for (int i = 1; i <= 10 ; i++){
            String weiBoName = "name" + i;
            int score = i;
            redisTemplate.opsForZSet().add(SCORE_KEY,weiBoName,score);
        }
    }

    public void add(String weiBoName){
        redisTemplate.opsForZSet().incrementScore(SCORE_KEY,weiBoName,1);
    }

    @GetMapping("/getOrderByScore")
    public void getOrderByScore(){
        List<Score> list = new ArrayList<Score>();
        Set<ZSetOperations.TypedTuple<Object>> rangeByScoreSet = redisTemplate.opsForZSet().rangeByScore(SCORE_KEY, 1, 10, 0, 10);
        Iterator iterator = rangeByScoreSet.iterator();
        while (iterator.hasNext()){
            ZSetOperations.TypedTuple<Object> next = (ZSetOperations.TypedTuple<Object>) iterator.next();
            Score score = new Score();
            score.setName((String) next.getValue());
            score.setScore(next.getScore());
            list.add(score);
        }
        System.out.println(list.toArray());
    }
}

使用hash存储对象

/**
 * @author 刘宇浩
 */
@RestController
@RequestMapping("/shop")
public class ShoppingController {

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String SHOPPING_KEY = "shopping:";

    @PostMapping("/addCart")
    public void addCart(@RequestBody Cart cart) {
        String key = SHOPPING_KEY + cart.getUserId();
        Boolean hasKey = redisTemplate.opsForHash().getOperations().hasKey(key);
        if (hasKey){
            redisTemplate.opsForHash().put(key,cart.getProductId().toString(),cart.getAmount());
        }else {
            redisTemplate.opsForHash().put(key,cart.getProductId().toString(),cart.getAmount());
            redisTemplate.expire(key,90, TimeUnit.DAYS);
        }
    }

    @PostMapping("/updateCart")
    public void updateCart(@RequestBody Cart cart){
        String key = SHOPPING_KEY + cart.getUserId();
        redisTemplate.opsForHash().put(key,cart.getProductId().toString(),cart.getAmount());
    }

    @PostMapping("/findAllAmount")
    public Long findAllAmount(@RequestParam Long userId){
        String key = SHOPPING_KEY + userId;
        return redisTemplate.opsForHash().size(key);
    }
}

String数据结构

/**
 * @author 刘宇浩
 */
@RestController
@RequestMapping("/redis/view")
public class ViewController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 计数方案
     * 微信阅读人数
     * 还未同步到数据库
     * @param id
     */
    @GetMapping("/getPeople")
    public void getPeople(Integer id) {
        String key = "people" + id;
        Long increment = stringRedisTemplate.opsForValue().increment(key);
        System.out.println(increment);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小颜-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值