SpringBoot進階教程(五十二)整合Redis


緩存現在幾乎是所有中大型網站都在用的必殺技,合理的利用緩存不僅能夠提升網站訪問速度,還能大大降低數據庫的壓力。Redis提供了鍵過期功能,也提供了靈活的鍵淘汰策略,所以,現在Redis用在緩存的場合非常多。

之前有兩篇博文(centos安裝RedisRedis五大數據類型的常用操作),分別介紹了Redis的安裝和Redis的常用操作。今天主要介紹介紹springboot整合Redis。

v應用場景

現在公司做的項目都偏重論壇/社區/社交類產品,所以對Redis的實用場景主要集中在排行榜,最新/最熱內容,Redis提供的有序集合數據類構能實現各種復雜的排行榜應用。還有點贊、踩、關注/被關注、共同好友等是社交網站的基本功能,社交網站的訪問量通常來說比較大,而且傳統的關系數據庫類型不適合存儲這種類型的數據,Redis提供的哈希、集合等數據結構能很方便的的實現這些功能。

還有很多應用場景,比如分布式會話和分布式鎖(分布式鎖感興趣的可以看我之前的一篇文章《Java分布式鎖,搞懂分布式鎖實現看這篇文章就對了》)等等,總之越來越廣泛。

v搭建Redis

1.1. 引入Redis

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>redis.clients</groupId>-->
            <!--<artifactId>jedis</artifactId>-->
            <!--<version>2.9.0</version>-->
        <!--</dependency>-->

注意redis.clients是我本地調試測試用的,可以忽略。

1.2. 添加RedisCacheConfig

package com.demo.Redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
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.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.concurrent.CountDownLatch;

/**
 * Created by toutou on 2019/1/20.
 */
@Configuration
@EnableCaching
public class RedisCacheConfig {
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));

        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }

    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    public class Receiver {


        private CountDownLatch latch;

        @Autowired
        public Receiver(CountDownLatch latch) {
            this.latch = latch;
        }

        public void receiveMessage(String message) {
            latch.countDown();
        }
    }
}

可以按需添加,也可以按需忽略。

1.3. 添加Redis配置,修改application.properties

# ----- Redis -------- #
# REDIS (RedisProperties)
# Redis數據庫索引(默認為0)
spring.redis.database=0  
# Redis服務器地址
spring.redis.host=10.168.11.129
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8  
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1  
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8  
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0  
# 連接超時時間(毫秒)
spring.redis.timeout=5000

1.4. 添加Service

package com.demo.service;

import com.demo.pojo.UserDetails;

/**
 * Created by toutou on 2018/10/15.
 */
public interface UserService {
    UserDetails getUserDetailsByUid(int uid);
    String getUserNameById(Integer uid);
    void setUserNameById(Integer uid, String userName);
}

UserServiceImpl

package com.demo.service;

import com.demo.dao.UserDetailsMapper;
import com.demo.dao.UserPositionMapper;
import com.demo.pojo.UserDetails;
import com.demo.pojo.UserPosition;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by toutou on 2018/10/15.
 */
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    UserDetailsMapper userDetailsMapper;

    @Autowired
    UserPositionMapper userPositionMapper;

    @Autowired
    StringRedisTemplate template;

    static final String KEY_USER_INFO__NAME = "com_demo_user_info_007_%s";

    public String getUserNameById(Integer uid){
        String userName = "未知用戶";
        try {
            userName = template.opsForValue().get(String.format(KEY_USER_INFO__NAME, uid));
            if (Strings.isNullOrEmpty(userName)) {
                // Redis中沒有就讀數據庫
                UserDetails userDetails = getUserDetailsByUid(uid);
                if (userDetails != null && !Strings.isNullOrEmpty(userDetails.getCity())) {
                    userName = userDetails.getCity();
                }
            }
        }catch(Exception e){
            System.out.println(e.toString());
        }

        return userName;

    }

    public void setUserNameById(Integer uid, String userName){
        template.opsForValue().set(String.format(KEY_USER_INFO__NAME, uid), userName);
    }

    public UserDetails getUserDetailsByUid(int uid){
        return userDetailsMapper.getUserDetailsByUid(uid);
    }

    
}

1.5. 添加RedisController

package com.demo.controller;

import com.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

/**
 * Created by toutou on 2019/1/20.
 */
@RestController
@Slf4j
public class RedisController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/getusernamebyid")
    public String getUserNameById(Integer uid)
    {
        return userService.getUserNameById(uid);
    }

    @RequestMapping(value = "/setusernamebyid")
    public String setUserNameById(Integer uid, String uname)
    {
        userService.setUserNameById(uid, uname);
        return "設置成功";
    }

    @RequestMapping(value = "/jedistest")
    public String jedisTest(){
        // 創建一個jedis對象
        Jedis jedis = new Jedis("ip", 6379);
        // 直接調用jedis對象的方法,方法名稱和redis的命令一致
        jedis.set("key1", "test01");
        String key1 = jedis.get("key1");
        System.out.println(key1 + " " + key1);
        // 關閉jedis
        jedis.close();
        return key1;
    }
}

注意jedisTest是我本地調試測試用的,可以忽略。

vRedis測試效果

SpringBoot進階教程(二十四)整合Redis

SpringBoot進階教程(二十四)整合Redis

v源碼地址

https://github.com/toutouge/javademosecond/tree/master/hellospringboot


作  者:請叫我頭頭哥
出  處:http://www.cnblogs.com/toutou/
關於作者:專注於基礎平台的項目開發。如有問題或建議,請多多賜教!
版權聲明:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
特此聲明:所有評論和私信都會在第一時間回復。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角推薦一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM