SpringBoot+Redis基本操作,实现排行榜功能

SpringBoot+Redis基本操作

    • SpringBoot引入Redis依赖
    • 配置application.yml
    • 注入RedisTemplate,还要有初始化RedisConnectionFactory
    • 在Controller中的使用

SpringBoot引入Redis依赖

 
        
        
        
            org.springframework.boot
            spring-boot-starter
            2.1.3.RELEASE
        


    
        org.springframework.boot
        spring-boot-starter-jdbc
    

        
        
            org.springframework.boot
            spring-boot-starter-web
            2.1.3.RELEASE
        

	   
        
        
            org.springframework.data
            spring-data-redis
            2.1.5.RELEASE
        

        
        
            redis.clients
            jedis
            2.9.0
        
		
		
        
        
            org.apache.commons
            commons-lang3
            3.8.1
        

        
        
        
            com.google.guava
            guava
            27.0.1-jre
        


    

配置application.yml

spring:
  redis:
    database: 0
    host: localhost
    port: 6379
    password: root
    pool:
      max-active: 8
      max-wait: -1
      max-idle: 8
      min-idle: 0
    timeout: 5000
server:
  port: 8081

注入RedisTemplate,还要有初始化RedisConnectionFactory


package com.rosam.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 自己的redisTemplate
 *
 * @author Song.aw
 * @create 2017-12-07 9:37
 **/
@Configuration
public class RedisConfig{

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Bean
    public RedisTemplate functionDomainRedisTemplate() {
        RedisTemplate redisTemplate = new RedisTemplate();
        initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }

    private void initDomainRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
    }


}

在Controller中的使用

package com.rosam.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录后保存用户名为userName,value为password
     * @param userName
     * @param password
     * @return
     */
    @GetMapping("/login")
    @ResponseBody
    public String login(@RequestParam("userName")String userName, @RequestParam("password")String password){
        redisTemplate.opsForValue().set(userName, password);
        redisTemplate.expire(userName,10,TimeUnit.SECONDS);
        return "success";
    }

    /**
     * 原子自增,设置过期时间
     * @param params
     * @return
     */
    @RequestMapping(value = "/incrementScore", method = RequestMethod.POST)
    @ResponseBody
    public String incrementScore(@RequestBody Map params) {
        String key = params.get("key").toString();
        Long value =(Long) redisTemplate.opsForValue().get(key);
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        entityIdCounter.expire(3, TimeUnit.SECONDS);//过期时间为3秒
        Long increment = entityIdCounter.getAndIncrement();
        redisTemplate.opsForValue().set(key,increment+value);
        return "success";
    }

    /**
     * 实现排序,热度,积分榜等功能,更多方法可以可以搜索zSetOperations
     * @return
     */
    @GetMapping(value = "rankScore")
    @ResponseBody
    public String rank(){
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        zSetOperations.add("score","one",1);
        zSetOperations.add("score","four",4);
        zSetOperations.add("score","three",110);
        zSetOperations.add("score","five",5);
        zSetOperations.add("score","six",6);
        //从子集中找到Smin<=score<=Smax的元素集合
        //value在此区间中的。
        Set set = zSetOperations.rangeByScore("score", 100,120);
        System.out.println("打印v1的值在100-120区间的"+set.size());

        //索引start<=index<=end的元素子集,返回泛型接口(包括score和value),正序
        //返回score和value,set中的前两个
        Set set1 = zSetOperations.rangeWithScores("score",0,1);

        //键为K的集合,索引start<=index<=end的元素子集,正序
        //返回排序后的value中的前两个
        Set set2 = zSetOperations.range("score",0,1);

        //键为K的集合,索引start<=index<=end的元素子集,倒序
        //返回排序后的最后两个
        Set set3 = zSetOperations.reverseRange("score",0,1);

        return null;
    }


    /**
     * 根据key获取value
     * @param key
     * @return
     */
    @GetMapping("/get")
    @ResponseBody
    public String getRedisVal(@RequestParam String key){
       String value = redisTemplate.opsForValue().get(key).toString();
       return value;
    }

    /**
     * 根据key设置value
     * @param key
     * @param value
     * @return
     */
    @GetMapping("/set")
    @ResponseBody
    public String setRedisVal(@RequestParam String key, @RequestParam Integer value){
        redisTemplate.opsForValue().set(key , value);
        return "success";
    }



}

你可能感兴趣的:(redis)