SpringBoot 整合 Redis 的简单案例

简介 Redis今天看了redis,只知道redis能做3件事:做缓存做非关系型数据库做消息中间件1).安装redis 在opt目录下,使用root用户cd /optmkdir rediswget http://download.redis.io/releases/redis-3.2.8.tar.gztar -zxvf redis-3.2.8.

🔔🔔好消息!好消息!🔔🔔

 如果您需要注册ChatGPT,想要升级ChatGPT4。凯哥可以代注册ChatGPT账号代升级ChatGPT4

有需要的朋友👉:微信号 kaigejava2022

Redis

今天看了redis, 只知道redis能做3件事:

  • 做缓存

  • 做非关系型数据库

  • 做消息中间件

1).安装redis 
在opt目录下,使用root用户

cd /opt
mkdir redis
wget http://download.redis.io/releases/redis-3.2.8.tar.gztar -zxvf redis-3.2.8.tar.gz cd redis-3.2.8/
make
cd /opt
chmod 777 -R redis12345678

2).测试安装redis是否成功 
这里写图片描述

重新开一个终端

这里写图片描述

3).在原有项目中引入redis,先在pom.xml添加redis的依赖

<!-- 添加redis -->  
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-redis</artifactId>
           <version>1.4.5.RELEASE</version>
        </dependency>123456

4).在application.properties中添加redis配置信息

#redis  spring.redis.hostName=127.0.0.1spring.redis.port=6379    spring.redis.pool.maxActive=8    spring.redis.pool.maxWait=-1    spring.redis.pool.maxIdle=8    spring.redis.pool.minIdle=0    spring.redis.timeout=0 12345678

5).新建一个config包,用来存放一些配置文件,新建RedisConfig.java

package com.hsp.config;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;@Configuration  @EnableCaching//开启注解  public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) {
       CacheManager cacheManager = new RedisCacheManager(redisTemplate);       return cacheManager;
    }    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
       RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
       redisTemplate.setConnectionFactory(factory);       return redisTemplate;
    }
}123456789101112131415161718192021222324252627

6).在service包中建立一个RedisService.java类

package com.hsp.sercice;public interface RedisService {    public void set(String key, Object value);  

    public Object get(String key);  

}123456789

7).RedisServiceImpl.java

package com.hsp.service.impl;import javax.annotation.Resource;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Service;import com.hsp.repository.UserRepository;import com.hsp.sercice.RedisService;@Servicepublic class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;    public void set(String key, Object value) {
        ValueOperations<String,Object> vo = redisTemplate.opsForValue();
         vo.set(key, value);
    }    public Object get(String key) {
        ValueOperations<String,Object> vo = redisTemplate.opsForValue();        return vo.get(key);
    }
}12345678910111213141516171819202122232425

8).UserController.java

package com.hsp.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import com.hsp.entity.User;import com.hsp.sercice.RedisService;import com.hsp.sercice.UserService;@Controller
@RequestMapping(path="/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    //从redis获取某个用户
    @RequestMapping(value = "/getuserfromredis", method = RequestMethod.GET)
    public @ResponseBody User getRedis(@RequestParam String key) {
        return (User)redisService.get(key);
    }

    //获取所有用户
    @RequestMapping(value = "/getusers", method = RequestMethod.GET)
    public @ResponseBody Page<User> list(Model model, Pageable pageable){
        return userService.findAll(pageable); 
    }

    //添加用户
    @GetMapping(value="/adduser")
    public @ResponseBody String addUser(@RequestParam String dictum,
            @RequestParam String password, @RequestParam String username) {
        User user = new User();
        user.setDictum(dictum);
        user.setPassword(password);
        user.setUsername(username);
        System.out.println(user);
        userService.saveUser(user);
        redisService.set(user.getId()+"", user);
        return "Saved";
    }
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051

9).测试 
这里写图片描述

10).这里有一点要注意,需要把存放在redis中的对象序列化,User.java

package com.hsp.entity;import java.io.Serializable;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToMany;import javax.persistence.Table;@Entity@Table(name="s_user")public class User implements Serializable {

    private static final long serialVersionUID = 1L;    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO)    private Integer id;    private String username;    private String password;    private String dictum;    @OneToMany(mappedBy = "user", fetch = FetchType. LAZY, cascade = {CascadeType. ALL})    private Set<Photo> setPhoto;    public Integer getId() {        return id;
    }    public void setId(Integer id) {        this.id = id;
    }    public String getUsername() {        return username;
    }    public void setUsername(String username) {        this.username = username;
    }    public String getPassword() {        return password;
    }    public void setPassword(String password) {        this.password = password;
    }    public String getDictum() {        return dictum;
    }    public void setDictum(String dictum) {        this.dictum = dictum;
    }    public Set<Photo> getSetPhoto() {        return setPhoto;
    }    public void setSetPhoto(Set<Photo> setPhoto) {        this.setPhoto = setPhoto;
    }    @Override
    public String toString() {        return "User [id=" + id + ", username=" + username + ", password="
                + password + ", dictum=" + dictum + ", setPhoto=" + setPhoto
                + "]";
    }
}


TopTop