springboot学习系列三:springboot集成Redis

 

 

目录

 

pom.xml中引入依赖

application.yml配置文件

测试redis样例


pom.xml中引入依赖

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-redis</artifactId>

            <version>2.3.1.RELEASE</version>

</dependency>

application.yml配置文件

server:

   port:  8090

spring:

  redis:

    database: 1  #Redis数据库索引(默认为0)

    host: 127.0.0.1 #Redis服务器地址

    #Redis服务器连接端口

    port: 6379

    #Redis服务器连接密码

    password:

    jedis:

      pool:

        max-active: 1000  #连接池最大连接数(只用负数值表示没有限制)

        max-wait: -1   #连接池最大阻塞等待时间(只用负数值表示没有限制)

        max-idle: 10   #连接池中的最大空闲连接

        min-idle: 2    #连接池中的最小空闲连接

#连接超时时间(毫秒)

    timeout: 5000

测试redis样例

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class DemoApplicationTests {
    
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedis(){

        redisTemplate.opsForValue().set("name","张三");

        String testName = (String) redisTemplate.opsForValue().get("name");

        System.out.println("从Redis中取值,看一下:"+testName);

        redisTemplate.opsForValue().set("name","李四");

        testName = (String) redisTemplate.opsForValue().get("name");

        System.out.println("重新赋值,测试,看一下结果:"+testName);

    }


}

Redis在springboot项目中应用

(1)实体类

package com.example.demo.entity;

public class User {

    private Integer id;

    private String userName;

    private String password;

    public Integer getId() {
        return id;
    }

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

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

    public void setUserName(String userName) {
        this.userName = userName;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

(2)mapper层

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserMapper {

    User getUser(Integer id);

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.example.demo.entity.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="userName" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>

  
  <sql id="Base_Column_List">
    id, name, password
  </sql>

  <select id="getUser" parameterType="java.lang.Integer" resultMap="BaseResultMap">

    select
    <include refid="Base_Column_List" />
    from user
    where id = #{id}

  </select>

</mapper>

(3)service层

package com.example.demo.service;

import com.example.demo.entity.User;

public interface UserService {

    public User getUser(Integer id);

}
package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;


    @Override
    public User getUser(Integer id) {

        String userId = String.valueOf(id);

        boolean flag = redisTemplate.hasKey(userId+" : "+userId);

        if(flag){

            System.out.println("从缓存中读取数据");

            String data = (String) redisTemplate.opsForValue().get(userId+" : "+userId);

            User user = JsonUtils.jsonToObject(data,User.class);

            return user;

        }else{

            System.out.println("从数据库中读取数据");

            User user = userMapper.getUser(id);

            redisTemplate.opsForValue().set(userId+" : "+userId,JsonUtils.objectToJson(user));

            redisTemplate.expire(userId+" : "+userId,3000, TimeUnit.SECONDS);

            return user;
        }

    }
}

(4)util工具类

package com.example.demo.util;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
	
	private static ObjectMapper MAPPER = new ObjectMapper();
	/**
	 * 将对象转化为json字符串
	 * @param data
	 * @return
	 */
	public static String objectToJson(Object data) {
		
		try {
			
			String string = MAPPER.writeValueAsString(data);
			
			return string;
			
		} catch (JsonProcessingException e) {
			
			e.printStackTrace();
		}
		
		return null;
		
	}
	/**
	 * 将json结果转化为对象
	 * @param <T>
	 * @param jsonData
	 * @param beanType
	 * @return
	 */
	public static <T> T jsonToObject(String jsonData,Class<T> beanType) {

			try {
				
				T t = MAPPER.readValue(jsonData, beanType);
				
				return t;
				
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		return null;
	}
	/**
	 * 将json对象转化为pojo对象list
	 * @param <T>
	 * @param jsonData
	 * @param beanType
	 * @return
	 */
	public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
		 
		JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
		
		try {
			
			List<T> list = MAPPER.readValue(jsonData, javaType);
			
			return list;
		
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		return null;
	}
}

(5)controller层测试

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private UserService userService;

    @GetMapping("/test")
    public User selectUserById(Integer id){

        User user = userService.getUser(id);

        return user;
    }

}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值