Springboot整合redis入门例子

首先要打开redis,然后创建springboot。

idea配置文件application.yml

spring:
  # REDIS (RedisProperties)
  redis:
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6379
    pool:
      # 连接池中的最大空闲连接
      max-idle: 8
      # 连接池中的最小空闲连接
      min-idle: 0
      # 连接池最大连接数(使用负值表示没有限制)
      max-active: 8
      # 连接池最大阻塞等待时间(使用负值表示没有限制)
      max-wait: -1
    # 连接超时时间(毫秒)
    timeout: 1000
    # Redis数据库索引(默认为0)
    database: 0
    # Redis服务器连接密码(默认为空)
    password: 123456

redis配置类RedisConfig

package com.example.demo2.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@PropertySource("classpath:application.yml")
public class RedisConfig {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private int database;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.pool.max-wait}")
    private long maxWait;

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setPassword(password);
        factory.setDatabase(database);
        factory.setTimeout(timeout);

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxActive);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWait);

        factory.setPoolConfig(jedisPoolConfig);

        return factory;
    }

    @Bean
    public RedisTemplate<String, User> redisTemplate() {
        RedisTemplate<String, User> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }
}

User类定义属性

package com.example.demo2.test;

public class User {
    String uid;
    String userName;
    String passWord;
    String name;

          public User() {
         }

         public User(String uid, String userName, String passWord, String name) {
           this.uid = uid;
           this.userName = userName;
           this.passWord = passWord;
           this.name = name;
        }

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

          public String getUid() {
             return uid;
         }

           public void setUid(String uid) {
                this.uid = uid;
             }

           public String getUserName() {
                return userName;
            }
            public void setUserName(String userName) {
                this.userName = userName;
         }
         public String getPassWrod() {
                 return passWord;
         }
         public void setPassWrod(String passWord) {
              this.passWord = passWord;
          }

        public String getName() {
                 return name;
         }

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

dao层

package com.example.demo2.test;

import redis.clients.jedis.Jedis;

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

public class UserDao {
    private static Jedis jedis;

            public UserDao(Jedis jedis) {
               this.jedis = jedis;
       }
    public void addUser(User user) {
                //首先保存user-id
                 jedis.sadd("useradd", "user-" + user.getUid());
                 //-----添加数据----------
                Map<String, String> map = new HashMap<String, String>();
                map.put("uid", user.getUid());
                map.put("userName", user.getUserName());
                map.put("passWord", user.getPassWrod());
                map.put("name", user.getName());
                jedis.hmset("user-" + user.getUid(), map);
            }

         /**
     * 获取单个User
     *
      * @return
     */
           public List<String> getById(String id) {
              if (exists()) {
                       return jedis.hmget("user-" + id, "id", "userName", "passWord", "name");
                }
              return null;
            }
    /**
     * 获取全部
 43      *
 44      * @return
 45      */
           public List<User> listAll() {
               List<User> list = new ArrayList<User>();
               User user = null;
               if (exists()) {
                       for (String useradd : jedis.smembers("useradd")) {
                               user = new User();
                               List<String> lists = jedis.hmget(useradd, "id", "userName", "passWord", "name");
                          // User user2= (User) jedis.hmget(useradd, "id", "userName", "passWord", "name");
                               user.setUid(lists.get(0));
                               user.setUserName(lists.get(1));
                               user.setPassWrod(lists.get(2));
                               user.setName(lists.get(3));
                               list.add(user);
                         }
                      return list;
                 }
                return null;
             }

           //删除全部
            public boolean delAll() {
              if (exists()) {
                         jedis.del("useradd");
                        return true;
                 }
                 return false;
             }

         //判断是否存在
            public boolean exists() {
                 return jedis.exists("useradd");
            }
}

contoller

package com.example.demo2;
import com.example.demo2.test.User;
import com.example.demo2.test.UserDao;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.List;
@RestController
@SpringBootApplication
public class Demo2Application {
    private static Jedis jedis =null;
	public static void main(String[] args) {
		SpringApplication.run(Demo2Application.class, args);
	}
@RequestMapping(value = "/hello", method = RequestMethod.GET)
    public List<User> TextController(){
    jedis = new Jedis("localhost");
    System.out.println("连接成功");
    //查看服务是否运行
    System.out.println("服务正在运行: "+jedis.ping());
    UserDao user = new UserDao(jedis);
    List<User> listUser=new ArrayList<User>();
    user.delAll();
    user.addUser(new User("21","ldl","123456","刘地林"));
    user.addUser(new User("31","oyl","123456","欧一乐"));
    user.addUser(new User("41","tyj","123456","唐玉棋"));
    user.addUser(new User("51","cs","123456","陈胜"));
    user.addUser(new User("61","gsq","123456","郭世棋"));
    for (User user1 : user.listAll()) {
        System.out.println(user1);
        listUser.add(user1);
    }
    return listUser;

}
}

pom.xml

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

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

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.4</version>
		</dependency>

		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.9.0</version>
		</dependency>

	</dependencies>

这样就可以运行了,访问网页;
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值