Spring Boot(四)整合Redis

1、创建项目并编辑pom文件

<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.github.ralgond</groupId>
	<artifactId>boot-redis</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
	</parent>
	
	<properties>
		<start-class>com.github.ralgond.bootredis.BootRedisMainApp</start-class>
	</properties>

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

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

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

2、添加application.yml到src/main/resources

server:
  port: 8888
  
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379

3、创建User类

package com.github.ralgond.bootredis.entity;

public class User {
	private Integer id;
    private String name;
    
	public User() {
	}
	public User(Integer id, String name) {
		this.id = id;
		this.name = name;
	}
	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;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}
}

4、添加RedisConfig类来配置RedisTemplate

这一步骤主要是将序列化方法从jdk改变成json。

package com.github.ralgond.bootredis;

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
	
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
	RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();

        // 注入数据源
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用GenericJackson2JsonRedisSerializer 替换默认序列化
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key-value结构序列化数据结构
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // hash数据结构序列化方式,必须这样否则存hash 就是基于jdk序列化的
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        // 启用默认序列化方式
        redisTemplate.setEnableDefaultSerializer(true);
        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);

        /// redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

5、添加主启动类

package com.github.ralgond.bootredis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.github.ralgond.bootredis.entity.User;

@SpringBootApplication
@RestController
public class BootRedisMainApp {
	
	@Autowired
	RedisTemplate<String, Object> redisTemplate;
	
	@RequestMapping(method=RequestMethod.GET, value="/user/add/{name}")
	public User addUser(@PathVariable("name") String name) {
		User user = new User(-1, name);
		redisTemplate.opsForValue().set(name, user);
		return user;
	}
	
	@RequestMapping(method=RequestMethod.GET, value="/user/{name}")
	public User getUser(@PathVariable("name") String name) {
		Object o = redisTemplate.opsForValue().get(name);
		System.out.println(o);
		return (User)o;
	}
	
	public static void main(String args[]) {
		SpringApplication.run(BootRedisMainApp.class, args);
	}
}

6、运行主启动类

在浏览器上输入http://localhost:8888/user/add/u4添加一个User类实例到redis中,如下图:

在浏览器上输入http://localhost:8888/user/u4便可从redis中取出name为u4的User类实例。

posted @ 2020-12-23 10:52  ralgo  阅读(190)  评论(0)    收藏  举报