springboot整合redis的脚手架

springboot整合redis的脚手架

前置步骤

  1. 修改pom文件
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javaye</groupId>
	<artifactId>spring2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring2</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

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

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>
  1. 添加redis信息
spring:
  redis:
    database: 0              #数据库
#    ssl:                    #是否开启ssl
#    timeout:                #超时时间
    host: 192.168.52.19         #Reids主机地址
    port: 6379              #Redis端口号
    password: $PASSWORD
    lettuce:                #使用 lettuce 连接池
      pool:
        max-active: 20      #连接池最大连接数(使用负值表示没有限制)
        max-wait: -1        #连接池最大阻塞等待时间(使用负值表示没有限制)
        min-idle: 0         #连接池中的最大空闲连接
        max-idle: 10        #连接池中的最小空闲连接
  1. 配置redis序列化
package com.javaye.spring2.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
* @Author: Java页大数据
* @Date: 2023-10-11:22:53
* @Describe:
*/
@Configuration
public class RedisConfig {

   /**
    * Redis 序列化配置
    */
   @Bean(name = "redisTemplate")
   public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
       RedisTemplate<String, Object> template = new RedisTemplate<>();
       template.setConnectionFactory(factory);
       Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
       ObjectMapper om = new ObjectMapper();
       om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
       om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
       jacksonSeial.setObjectMapper(om);
       template.setValueSerializer(jacksonSeial);
       template.setKeySerializer(new StringRedisSerializer());
       template.setHashKeySerializer(new StringRedisSerializer());
       template.setHashValueSerializer(jacksonSeial);
       template.afterPropertiesSet();
       return template;
   }
}

小demo

  1. service端
package com.javaye.spring2.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: Java页大数据
 * @Date: 2023-10-11:21:06
 * @Describe:
 */
@Service
public class AllService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

//    使用StringRedisTemplate要用@Resource来引入,无法用@Autowired引入!
//    @Resource
//    StringRedisTemplate stringRedisTemplate;

    public String getKey(Object key){
        String s = (String) redisTemplate.opsForValue().get(key);
//        ValueOperations opsForValue = redisTemplate.opsForValue();
//        return opsForValue.get(key);
        return s;
    }

    public void setKeyValue(String key, String value){
        redisTemplate.opsForValue().set(key, value);
    }

}
  1. controller端
package com.javaye.spring2.controller;

import com.javaye.spring2.service.AllService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Java页大数据
 * @Date: 2023-10-11:21:05
 * @Describe:
 */
@RestController
public class AllController {
    @Autowired
    private AllService service;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @GetMapping("/set/{key}/{value}")
    public void setKey(@PathVariable String key, @PathVariable String value){
        service.setKeyValue(key, value);
    }

    @GetMapping("/get/{key}")
    public String getkey(@PathVariable String key){
        return service.getKey(key);
    }
}
  1. 开启redis服务端,并在浏览器访问:http://localhost:8080/set/k1/v11111 或者 http://localhost:8080/get/k1
  2. 在redis客户端查看是否设置了k1的value为v11111
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值