1. 程式人生 > >Spring boot集成Redis(2)—RedisTemplate的使用來存儲Map集合

Spring boot集成Redis(2)—RedisTemplate的使用來存儲Map集合

gre ops could 批量 values tor key值 idata repos

前言:上一篇文章我們用的是StringRedisTemplate,但是它存在一點問題,也迫使我重新寫了代碼,問題是:在我們往緩存中存入數字形式的String類型時,我們在利用Spring could將獲取到的數據發送到另一服務時,我們發現數據已經被強轉為Integer類型了,因為我們可能傳輸的數據龐大,類型多樣,為了統一類型,以及開發方便,所以我將緩存改成RedisTemplate這種類型,進行增刪改查的操作,文中沒有特別舉例更新操作,其更新操作與添加操作一樣,當key一樣時進行添加就會覆蓋原value值,完成更新。RedisTemplate需要我們自己去配置它並進行實例化。接下來,舉例子,上代碼:
首先建立Spring boot項目添加Redis依賴
技術分享圖片
下載導入IDE,我們觀察pom.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>redis</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <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>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.配置application.properties

#redis
spring.redis.host=主機地址
spring.redis.password=admin
spring.redis.port=6379
spring.redis.timeout=10000
spring.redis.jedis.pool.max-idle=200 
spring.redis.jedis.pool.min-idle=300000    
spring.redis.jedis.pool.max-active=400
spring.redis.jedis.pool.max-wait=10000

2.我們寫配置配置類實例化RedisTemplate

package com.test.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.connection.RedisConnectionFactory;

@Configuration
public class RedisConfig {

    /**
     * 實例化 RedisTemplate 對象
     *
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 設置數據存入 redis 的序列化方式,並開啟事務
     * 
     * @param redisTemplate
     * @param factory
     */
    private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
        // 如果不配置Serializer,那麽存儲的時候缺省使用String,如果用User類型存儲,那麽會提示錯誤User can‘t cast to
        // String!
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 開啟事務
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.setConnectionFactory(factory);
    }

}

3.寫緩存操作的Service層,進行增刪改查方法的定義:

package cn.com.dhcc.idatabus.admin.console.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Service;

@Service
public class RedisService {

    @Resource
    private RedisTemplate<String,Object> template;

    /**
     * 存儲數據或修改數據
     * 
     * @param modelMap
     * @param mapName
     */
    public void setKey(String mapName, Map<String, Object> modelMap) {
        HashOperations<String, String, Object> hps = template.opsForHash();
        hps.putAll(mapName, modelMap);
    }

    /**
     * 獲取數據Map
     * 
     * @param mapName
     * @return
     */
    public Map<String, Object> getMapValue(String mapName) {
        HashOperations<String, String, Object> hps = this.template.opsForHash();
        return hps.entries(mapName);

    }

    /**
     * 獲取數據value
     * 
     * @param mapName
     * @param hashKey
     * @return
     */
    public Object getValue(String mapName, String hashKey) {
        HashOperations<String, String, Object> hps = this.template.opsForHash();
        return hps.get(mapName, hashKey);

    }

    /**
     * 批量刪除緩存數據
     * 
     * @param keys
     */
    public void deleteData(List<String> keys) {
        // 執行批量刪除操作時先序列化template
        template.setKeySerializer(new JdkSerializationRedisSerializer());
        template.delete(keys);
    }

}

4.本次例子的實體類

package com.test.redis.entity;

public class User {
    private Integer id;
    private String name;
    private String password;

    public User() {
        super();
    }

    public User(Integer id, String name, String password) {
        super();
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
    }

}

5.編寫Controller層,來實現緩存的操作

package com.test.redis.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.redis.entity.User;
import com.test.redis.service.RedisService;

@Controller
public class UserController {

    private static final String mapName="mapName";
    @Autowired
    private RedisService redisService;

    @GetMapping( "/templateAdd.do")
    @ResponseBody
    public Map<String, Object> addUser(HttpServletRequest request){
        Map<String, Object> modelMap=new HashMap<String,Object>();
        User user=new User();
        user.setName("hehename");
        user.setPassword("hehePassword");
        //存放hash值
        modelMap.put("name", user.getName());
        modelMap.put("password", user.getPassword());
        redisService.setKey(mapName, modelMap);
        //獲取map集合
        Map<String, Object> modelMap1= redisService.getMapValue(mapName);
        Object value= redisService.getValue(mapName, "name");
        System.out.println(" value : "+value);
        modelMap1.put("從緩存中根據key取到的value", value);
        return modelMap1;
    }

    @GetMapping( "/templateDelete.do")
    @ResponseBody
    public Map<String, Object> deleteUser(HttpServletRequest request){
        //獲取即將刪除的key值,這裏我們做的批量刪除
        List<String> keys=new ArrayList<>();
        keys.add("heheanme");
        //開始執行刪除操作
        redisService.deleteData(keys);
        //獲取map集合
        Map<String, Object> modelMap1= redisService.getMapValue(mapName);
        Object value= redisService.getValue(mapName, "name");
        System.out.println(" value : "+value);
        modelMap1.put("從緩存中根據key取到的value", value);
        return modelMap1;
    }

}

接下來,我們訪問Controller路徑
(1)http://localhost:8081/templateAdd.do
結果:
技術分享圖片
(2)http://localhost:8081/templateDelete.do
結果:
技術分享圖片

Spring boot集成Redis(2)—RedisTemplate的使用來存儲Map集合